diff --git a/foliator.py b/foliator.py index 17e0132..eca5949 100755 --- a/foliator.py +++ b/foliator.py @@ -34,6 +34,30 @@ def append_folio_A6(input_pdf, offset, size, append_to): dpage.merge_page(ipage) return writer +# Tries to find a partition as +# num_sheets = max_folio_size * a + (max_folio_size - k) * b +# where k is minimal. We let n = max_folio_size and L = num_sheets. +# Note that when L > n^2, then k = 1 must succeed. +def find_partition(num_sheets, max_folio_size): + max_a = num_sheets // max_folio_size + for k in range(1, max_folio_size): + # We want to solve a*k = L (mod n-k). This happens iff + # a*k' = L' (mod m') where k,L,m are divided by their gcd. + # Then, if k' and m' have a common factor, L' doesn't have it and there + # are no solutions. Otherwise, there's one solution mod m'. + g = math.gcd(max_folio_size - k, k, num_sheets) + mprime = (max_folio_size - k)//g + kprime = k//g + Lprime = num_sheets//g + if (math.gcd(kprime, mprime) > 1): + continue + a_mod_mprime = (pow(kprime, -1, mprime) * Lprime) % mprime + tosub = (max_a - a_mod_mprime + mprime) % mprime + # If we're a bit above, substract only a little. But a bit below implies + # substracting almost mprime. + candidate = max_a - tosub + if (candidate >= 0): + return (candidate, k) # Interprets input_pdf as a list of A6 pages, and appends to append_to with # A5 pages using the following rules: