man number-theory/integer-division

lesson 2 of 27 · Divisibility and the Euclidean algorithm

Integer division, floors and ceilings

lib / Number theory for competitive programming 18 mindraft

checked against: proofs in the text, code tested with Python 3.15.2

code: toothywalrus/cp-math@lesson-02

How many multiples of 4 lie between −9 and 13? Counting by hand gives 6: −8, −4, 0, 4, 8, 12. The formula that does it for ranges of length 101810^{18} is one line, ⌊13/4⌋−⌊−10/4⌋=3−(−3)\lfloor 13/4 \rfloor - \lfloor -10/4 \rfloor = 3 - (-3), and it gives 5 if you type it into C++. This lesson pins down what integer division means for every sign, in Python and in C++, then uses floors and ceilings to count, and ends with integer square roots, where floats fail quietly from about 4.5⋅10154.5 \cdot 10^{15} on.

The code is in cp-math at tag lesson-02, in cpmath/division.py. Its tests compare every function with brute force, and python3 -m cpmath.lesson02 prints every Python output on this page. The C++ output comes from demos/division.cpp in the same repo.

Division with remainder

Dividing 17 by 5 gives quotient 3 and remainder 2: 17=3⋅5+217 = 3 \cdot 5 + 2. For negative numbers there are two reasonable answers, and languages disagree, so it pays to start from the theorem that fixes one of them.

Theorem (division with remainder). For integers aa and b>0b > 0 there is exactly one pair of integers q,rq, r with

a=qb+r,0≤r<b,a = qb + r, \qquad 0 \le r < b,

and q=⌊a/b⌋q = \lfloor a/b \rfloor, the largest integer that is at most a/ba/b.

Proof. Existence: take q=⌊a/b⌋q = \lfloor a/b \rfloor and r=a−qbr = a - qb. From q≤a/b<q+1q \le a/b < q + 1, multiplying by b>0b > 0 gives qb≤a<qb+bqb \le a < qb + b, so 0≤r<b0 \le r < b. Uniqueness: if a=qb+r=q′b+r′a = qb + r = q'b + r' with both remainders in [0,b)[0, b), then b(q−q′)=r′−rb(q - q') = r' - r, and ∣r′−r∣<b\lvert r' - r\rvert < b. The only multiple of bb strictly between −b-b and bb is 0, so q=q′q = q' and r=r′r = r'. ■\blacksquare

Python follows this theorem: a // b is ⌊a/b⌋\lfloor a/b \rfloor for every sign of aa and bb, a % b is what is left, and a == (a // b) * b + a % b always holds. The language reference says so in those words. For b<0b < 0 the floor still decides, and the remainder then lies in (b,0](b, 0]: it always has the sign of the divisor.

 7 //  3 =  2    7 %  3 =  1   trunc_div =  2   trunc_mod =  1
-7 //  3 = -3   -7 %  3 =  2   trunc_div = -2   trunc_mod = -1
 7 // -3 = -3    7 % -3 = -2   trunc_div = -2   trunc_mod =  1
-7 // -3 =  2   -7 % -3 = -1   trunc_div =  2   trunc_mod = -1
divmod(-7, 3) -> (-3, 2)

The last two columns are what C++ computes, as the next section shows.

What C++ does instead

In C++, / on integers truncates toward zero: it drops the fractional part, so −7/3=−2.33…-7/3 = -2.33\ldots becomes −2-2, not −3-3. The remainder is defined by the same identity, (a / b) * b + a % b == a, so it takes the sign of the dividend: -7 % 3 is −1-1. The standard has required this since C++11; C++98 left the rounding direction to the implementation, and cppreference lists the change as a defect report against C++98.

Both conventions agree when the true quotient is non-negative. They differ exactly when the quotient is negative and not an integer, and then truncation is one more than the floor. That gives the conversions, copied from demos/division.cpp:

long long floor_div(long long a, long long b) {
    long long q = a / b;
    if (a % b != 0 && ((a < 0) != (b < 0))) q--;
    return q;
}
long long ceil_div(long long a, long long b) {
    long long q = a / b;
    if (a % b != 0 && ((a < 0) == (b < 0))) q++;
    return q;
}
// The remainder Python's % gives: 0 <= r < b for b > 0.
long long floor_mod(long long a, long long b) {
    long long r = a % b;
    if (r != 0 && ((r < 0) != (b < 0))) r += b;
    return r;
}

ceil_div is the mirror image: truncation equals the ceiling when the quotient is negative or exact, and is one less than it otherwise. The demo checks all three against a search over every pair with ∣a∣,∣b∣≤60\lvert a\rvert, \lvert b\rvert \le 60. Built with Apple clang 21 for arm64 (clang++ -std=c++17 -fsanitize=undefined), it prints:

demos/division.cpp:93:15: runtime error: division of -2147483648 by -1 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior demos/division.cpp:93:15 
C++ / and % on every sign:
   7 /  3 =  2    7 %  3 =  1
  -7 /  3 = -2   -7 %  3 = -1
   7 / -3 = -2    7 % -3 =  1
  -7 / -3 =  2   -7 % -3 = -1
floor_div, ceil_div, floor_mod: 14520 pairs checked, 0 wrong
floor_div(-7, 3) = -3, ceil_div(-7, 3) = -2, floor_mod(-7, 3) = 2
(a + b - 1) / b with a = -7, b = 3: -1 (the ceiling is -2)
multiples of 4 in [-9, 13]: hi / k - (lo - 1) / k = 5, with floor_div: 6
sizeof(double) = 8, sizeof(long double) = 8, LDBL_MANT_DIG = 53
n = 999999999999999999: (long long)sqrt(n) = 1000000000, (long long)sqrtl(n) = 1000000000, isqrt(n) = 999999999
n = 4503599761588224: (long long)sqrt(n) = 67108865, (long long)sqrtl(n) = 67108865, isqrt(n) = 67108864
n = 9223372036854775807: (long long)sqrt(n) = 3037000499, (long long)sqrtl(n) = 3037000499, isqrt(n) = 3037000499
isqrt: 6915968 values checked, 0 wrong
INT_MIN / -1 = -2147483648

The sanitizer’s complaint is about the last line. It comes first here because this output was captured to a file, where the program’s own output is buffered and the sanitizer’s is not; on a terminal it appears just before the last line. Two divisions are undefined behaviour in C++: by zero, and any whose quotient does not fit the type. The only such quotient for int is −231/(−1)=231-2^{31} / (-1) = 2^{31}. This build printed −231-2^{31}, but undefined means a different compiler or flag may do anything else. Python raises ZeroDivisionError for the first and has no second.

Going the other way, a Python solution sometimes has to reproduce C’s truncation, because a problem defines division that way:

def trunc_div(a, b):
    """a / b rounded toward zero, as C and C++ do (b != 0)."""
    q = abs(a) // abs(b)
    return q if (a < 0) == (b < 0) else -q


def trunc_mod(a, b):
    """The remainder that goes with trunc_div: C and C++'s a % b.
    It has the sign of a, and a == trunc_div(a, b) * b + trunc_mod(a, b)."""
    return a - trunc_div(a, b) * b

The shortcut int(a / b) gives the same result as long as ∣a∣<253\lvert a\rvert < 2^{53}, which covers 32-bit inputs. The reason: CPython rounds a / b on ints to the nearest double (CPython issue 1811). If a/ba/b is not an integer it is at least 1/∣b∣1/\lvert b\rvert away from one, while rounding moves it by at most half the spacing of doubles there, which is at most ∣a/b∣⋅2−53<1/∣b∣\lvert a/b\rvert \cdot 2^{-53} < 1/\lvert b\rvert. So rounding never reaches the next integer. The tests check this on 20,000 random pairs. Above 2532^{53} it fails, as the next section shows.

Ceilings without floats

Some answers are a ceiling: how many boxes of size bb hold aa items, how many hours a pile takes at a given speed. Negating turns a ceiling into a floor, ⌈x⌉=−⌊−x⌋\lceil x \rceil = -\lfloor -x \rfloor, and in Python that is one expression:

def ceil_div(a, b):
    """The ceiling of a / b, for any integers a and b != 0."""
    return -(-a // b)

The other common form is ⌈a/b⌉=⌊(a+b−1)/b⌋\lceil a/b \rceil = \lfloor (a + b - 1)/b \rfloor for b>0b > 0. Proof: write a=qb+ra = qb + r with 0≤r<b0 \le r < b. If r=0r = 0, then (a+b−1)/b=q+(b−1)/b(a + b - 1)/b = q + (b-1)/b, whose floor is q=a/bq = a/b. If r≥1r \ge 1, then (a+b−1)/b=q+1+(r−1)/b(a + b - 1)/b = q + 1 + (r - 1)/b with 0≤(r−1)/b<10 \le (r-1)/b < 1, so the floor is q+1=⌈a/b⌉q + 1 = \lceil a/b \rceil. ■\blacksquare The proof uses the floor, so in C++ use it only for a≥0a \ge 0: the demo above shows (-7 + 3 - 1) / 3 giving −1-1 where the ceiling is −2-2. It can also overflow when aa is near the top of the type.

What not to write is math.ceil(a / b). The / converts to a double, which has 53 bits of mantissa, so integers above 253=90071992547409922^{53} = 9007199254740992 are not all representable:

a = 10**18 + 1, b = 2: math.ceil(a / b) = 500000000000000000, ceil_div(a, b) = 500000000000000001
int((10**18 - 1) / 1) = 1000000000000000000, (10**18 - 1) // 1 = 999999999999999999

Both errors are silent. With integers up to 101810^{18}, the common contest limit, every division should stay in //.

Two identities for floors

Two facts about floors come up in almost every derivation. For a real xx and an integer nn,

⌊x+n⌋=⌊x⌋+n,\lfloor x + n \rfloor = \lfloor x \rfloor + n,

because ⌊x⌋+n\lfloor x \rfloor + n is an integer at most x+nx + n, and the next integer up is more than x+nx + n. And dividing twice is dividing once by the product: for an integer nn and integers a,b>0a, b > 0,

⌊⌊n/a⌋b⌋=⌊nab⌋.\left\lfloor \frac{\lfloor n/a \rfloor}{b} \right\rfloor = \left\lfloor \frac{n}{ab} \right\rfloor.

Proof. Divide twice with remainder: n=q1a+r1n = q_1 a + r_1 with 0≤r1<a0 \le r_1 < a, then q1=q2b+r2q_1 = q_2 b + r_2 with 0≤r2<b0 \le r_2 < b. Then n=q2⋅ab+(r2a+r1)n = q_2 \cdot ab + (r_2 a + r_1), and 0≤r2a+r1≤(b−1)a+(a−1)=ab−10 \le r_2 a + r_1 \le (b-1)a + (a-1) = ab - 1. By the uniqueness in the theorem, q2q_2 is the quotient of nn by abab. ■\blacksquare

So n // a // b == n // (a * b) for every sign of n, which is handy when a * b would overflow in C++. C++’s truncation obeys the same identity: for negative nn it is minus the floor of −n-n, and the identity holds for −n-n.

1000 // 7 // 11 = 12, 1000 // 77 = 12
-1000 // 7 // 11 = -13, -1000 // 77 = -13

Counting multiples in a range

The multiples of k>0k > 0 are the numbers kjkj for integers jj. The largest one that is at most xx is k⌊x/k⌋k \lfloor x/k \rfloor: by the definition of the floor, j≤x/kj \le x/k exactly when j≤⌊x/k⌋j \le \lfloor x/k \rfloor. So the multiples in [L,R][L, R] are kjkj for jj from ⌊(L−1)/k⌋+1\lfloor (L-1)/k \rfloor + 1 to ⌊R/k⌋\lfloor R/k \rfloor, and there are

⌊Rk⌋−⌊L−1k⌋\left\lfloor \frac{R}{k} \right\rfloor - \left\lfloor \frac{L-1}{k} \right\rfloor

of them, for any L≤RL \le R, negative or not. The figure steps through it, then repeats the subtraction with C++’s truncation:

Counting the multiples of 4 in [−9,13][-9, 13]. Trace from python3 -m cpmath.multiples_trace -9 13 4 in cp-math.

In C++, −10/4-10 / 4 truncates to −2-2, pointing at −8-8, which is inside the range, so −8-8 is not counted. With L≥1L \ge 1 both numerators are non-negative and plain / is fine; with possibly negative LL, use floor_div. In Python:

def count_multiples(lo, hi, k):
    """How many multiples of k (k > 0) lie in [lo, hi]. Any signs."""
    if lo > hi:
        return 0
    return hi // k - (lo - 1) // k


def count_congruent(lo, hi, r, k):
    """How many x in [lo, hi] have x % k == r % k (k > 0)."""
    return count_multiples(lo - r, hi - r, k)

The second function shifts the range: x≡r(modk)x \equiv r \pmod k means k∣x−rk \mid x - r, and x−rx - r runs over [lo−r,hi−r][lo - r, hi - r]. Numbers divisible by aa or bb are counted by adding both counts and subtracting the numbers counted twice, which are the multiples of lcm⁡(a,b)\operatorname{lcm}(a, b) (lesson 1); exercise 3 below is one. On this section’s examples:

multiples of 4 in [-9, 13]: [-8, -4, 0, 4, 8, 12]
13 // 4 = 3  (-9 - 1) // 4 = -3  count = 6
C++-style: trunc(13 / 4) - trunc(-10 / 4) = 3 - (-2) = 5
multiples of 7 in [10**18, 2*10**18]: 142857142857142857
x in [1, 100] with x % 7 == 3: 14 [3, 10, 17] ...

The tests compare count_multiples with a loop over the range for every −25≤L≤R≤25-25 \le L \le R \le 25 and 1≤k≤111 \le k \le 11, and on 2,000 random short ranges starting anywhere in [−1018,1018][-10^{18}, 10^{18}]; and count_congruent for every −15≤L≤R≤15-15 \le L \le R \le 15, 1≤k≤71 \le k \le 7 and −8≤r≤8-8 \le r \le 8.

Integer square roots

The integer square root of n≥0n \ge 0 is ⌊n⌋\lfloor \sqrt n \rfloor, the largest xx with x2≤nx^2 \le n. Python has it as math.isqrt (since 3.8; in 3.15 it is math.integer.isqrt, and math.isqrt is the same function, kept as a soft-deprecated alias). The tempting int(math.sqrt(n)) goes through a double and can be off by one:

int(math.sqrt(10**18 - 1)) = 1000000000, math.isqrt = 999999999, isqrt = 999999999
k = 67108865, n = k*k - 1 = 4503599761588224: int(math.sqrt(n)) = 67108865, math.isqrt(n) = 67108864

The first fails because 1018−110^{18} - 1 is not a double: it rounds to 101810^{18} before the square root is taken. The second fails even though n<253n < 2^{53} is exact: k2−1\sqrt{k^2 - 1} is about k−1/(2k)k - 1/(2k), and when k>226k > 2^{26}, 1/(2k)1/(2k) is less than half the spacing of doubles near kk, so the correctly rounded square root is kk itself. A scan of every kk (python3 -m cpmath.lesson02 --scan, eight seconds) finds k=67108865=226+1k = 67108865 = 2^{26} + 1 to be the first for which k2−1k^2 - 1 fails. That also shows that nothing below 671088642≈4.5⋅101567108864^2 \approx 4.5 \cdot 10^{15} fails: below 2532^{53}, int(math.sqrt(n)) never decreases as nn grows and is never below the right answer, so if it fails anywhere on a stretch [k2,(k+1)2−1][k^2, (k+1)^2 - 1], it also fails at the stretch’s last number.

Newton’s method in integers computes it exactly for any size:

def isqrt(n):
    """The largest x with x*x <= n, for an integer n >= 0, by Newton's
    method on integers. Every step is exact, so this works for any size.

    It starts at a power of two that is at least sqrt(n). From any
    x >= isqrt(n) the next value never drops below isqrt(n), and it is
    strictly smaller while x > isqrt(n); so the loop stops exactly at
    isqrt(n).
    """
    if n < 0:
        raise ValueError("isqrt of a negative number")
    if n == 0:
        return 0
    x = 1 << ((n.bit_length() + 1) // 2)    # n < 2**bits, so x > sqrt(n)
    y = (x + n // x) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

Why it is correct. Let s=⌊n⌋s = \lfloor \sqrt n \rfloor and x≥1x \ge 1. The step computes y=⌊t/2⌋y = \lfloor t/2 \rfloor with t=x+⌊n/x⌋=⌊x+n/x⌋t = x + \lfloor n/x \rfloor = \lfloor x + n/x \rfloor (the first identity). By the inequality of arithmetic and geometric means, x+n/x≥2n≥2sx + n/x \ge 2\sqrt n \ge 2s, and 2s2s is an integer, so t≥2st \ge 2s and y≥sy \ge s: the iteration never undershoots. If x>sx > s, then x≥s+1x \ge s + 1, so x2>nx^2 > n and n/x<xn/x < x, so t<2xt < 2x, t≤2x−1t \le 2x - 1 and y<xy < x. The start is at least ss, so the values strictly decrease while they are above ss and never go below it; the loop stops only when y≥xy \ge x, which can happen only at x=sx = s. ■\blacksquare

It converges fast; the counts are steps after the starting power of two:

isqrt_steps(10**18 - 1) = [1073741824, 1002532199, 1000003197, 1000000000, 999999999]
steps after the start: 10**18 - 1: 4  2**200: 6  3**2000: 8

In C++ there is no isqrt. Take the floating-point guess and correct it, comparing by division so that (r+1)2(r + 1)^2 never has to fit:

long long isqrt(long long n) {
    long long r = (long long)std::sqrt((double)n);
    while (r > 0 && r > n / r) r--;              // r*r > n
    while (r + 1 <= n / (r + 1)) r++;            // (r+1)*(r+1) <= n
    return r;
}

The demo checks it at k2−1k^2 - 1, k2k^2 and k2+1k^2 + 1 for every kk up to 2⋅1062 \cdot 10^6, every 9973rd kk after that, and the last thousand up to the largest square in a long long: 6,915,968 values. A common fix is sqrtl, but on this machine long double is the same 64-bit type as double (LDBL_MANT_DIG = 53 above), so sqrtl fails in the same places. The correction loops do not depend on how good the first guess is.

Two uses. The number of perfect squares in [L,R][L, R] for L≥1L \ge 1 is ⌊R⌋−⌊L−1⌋\lfloor \sqrt R \rfloor - \lfloor \sqrt{L-1} \rfloor, the same subtraction as for multiples. And the smallest xx with x2≥nx^2 \ge n, for n≥1n \ge 1, is 1 + math.isqrt(n - 1), as the Python documentation suggests.

Practice problems

Each needs an idea from this lesson. Links go to the problem pages; the one line is what to use, not the statement.

Try it yourself

  1. What are 17 // -5, 17 % -5, -17 // 5 and -17 % 5 in Python? What are -17 / 5 and -17 % 5 in C++?
  2. How many integers in [−100,100][-100, 100] are multiples of 7? How many leave remainder 3 when divided by 7 (in Python’s sense)?
  3. How many integers in [1,1018][1, 10^{18}] are divisible by 6 or by 10?
  4. Prove that ⌈a/b⌉=⌊(a−1)/b⌋+1\lceil a/b \rceil = \lfloor (a-1)/b \rfloor + 1 for integers aa and b>0b > 0.
  5. How many perfect squares lie in [1017,1018][10^{17}, 10^{18}]?
  6. In C++, (a % b + b) % b is a common way to get Python’s a % b for b>0b > 0. Why does it work, and for which long long values of bb can it overflow?

Answers

Each one is asserted in tests/test_lesson02.py, by brute force where the numbers are small enough.

Show the answers
  1. Python: −4-4, −3-3, −4-4, 33. C++: −3-3 and −2-2.
  2. 29 multiples (⌊100/7⌋−⌊−101/7⌋=14−(−15)\lfloor 100/7 \rfloor - \lfloor -101/7 \rfloor = 14 - (-15)), and 28 numbers with remainder 3 (from −95-95 to 94).
  3. ⌊n/6⌋+⌊n/10⌋−⌊n/30⌋=233333333333333333\lfloor n/6 \rfloor + \lfloor n/10 \rfloor - \lfloor n/30 \rfloor = 233333333333333333 for n=1018n = 10^{18}, since lcm⁡(6,10)=30\operatorname{lcm}(6, 10) = 30.
  4. Write a=qb+ra = qb + r with 0≤r<b0 \le r < b. If r=0r = 0, then a−1=(q−1)b+(b−1)a - 1 = (q-1)b + (b-1), so the right side is (q−1)+1=q=a/b(q - 1) + 1 = q = a/b. If r≥1r \ge 1, then a−1=qb+(r−1)a - 1 = qb + (r - 1) with 0≤r−1<b0 \le r - 1 < b, so the right side is q+1=⌈a/b⌉q + 1 = \lceil a/b \rceil.
  5. 683772234: ⌊1018⌋−⌊1017−1⌋=109−316227766\lfloor \sqrt{10^{18}} \rfloor - \lfloor \sqrt{10^{17} - 1} \rfloor = 10^9 - 316227766.
  6. a % b lies in (−b,b)(-b, b) and has the right remainder mod bb; adding bb keeps the remainder and makes the value positive, and C++’s % on non-negative numbers agrees with Python’s. The sum a % b + b is less than 2b2b, so it cannot overflow for b≤262b \le 2^{62}. For larger bb it can: a=262+1a = 2^{62} + 1, b=262+2b = 2^{62} + 2 gives a sum above 263−12^{63} - 1.

Sources

  • Python language reference, Binary arithmetic operations: // is division with the floor applied, % has the sign of its second operand, and x == (x//y)*y + (x%y).
  • Python documentation: math.integer (isqrt, and 1 + isqrt(n - 1) for the ceiling) and math (the soft-deprecated aliases, isqrt added in 3.8).
  • cppreference, Arithmetic operators: integer division truncates toward zero, (a / b) * b + a % b == a, and division by zero or an unrepresentable quotient is undefined; the defect reports CWG 614 and 1450.
  • Python issue 1811, “True division of integers could be more accurate”: the change that made a / b on ints correctly rounded.
  • Wikipedia, Euclidean division: the division theorem and its proof.
  • Wikipedia, Floor and ceiling functions, sections “Equivalences”, “Quotients” and “Nested divisions”: ⌊x+n⌋=⌊x⌋+n\lfloor x + n \rfloor = \lfloor x \rfloor + n, ⌈n/m⌉=⌊(n+m−1)/m⌋=⌊(n−1)/m⌋+1\lceil n/m \rceil = \lfloor (n + m - 1)/m \rfloor = \lfloor (n-1)/m \rfloor + 1 for m>0m > 0, and the nested-division identity.
  • Wikipedia, Integer square root: Newton’s method with integer division (section “Using only integer division”) and the rule of stopping at the first kk with xk+1≥xkx_{k+1} \ge x_k (section “Generalization to Nth roots”).
  • R. L. Graham, D. E. Knuth, O. Patashnik, Concrete Mathematics, 2nd ed., chapter 3, “Integer Functions”: floors, ceilings and their identities at length.

ls number-theory/

Divisibility and the Euclidean algorithm

  • 01 GCD, Euclid, and Bézout draftWhy gcd(a, b) = gcd(b, a mod b), why it takes so few steps, extended Euclid and ax + by = c. Unlocks gcd-of-array, water jug and lcm problems.
  • 02 Integer division, floors and ceilings draft// and % on negative numbers in Python and C++, ceiling division without floats, math.isqrt. Unlocks problems whose answer is a count of multiples in a range.
  • 03 GCD over arrays and subarrays draftPrefix and suffix gcds, the gcd of differences, why a subarray's gcd changes only a logarithmic number of times. Unlocks subarray-gcd counting and remove-one-element problems.

Primes and factorization

  • 04 Primality and factoring by trial division draftWhy checking up to the square root suffices, and how far that goes in a time limit. Unlocks single-number primality and factorization queries.
  • 05 The sieve of Eratosthenes plannedCrossing out multiples from p squared, its n log log n cost, and a fast bytearray version in Python. Unlocks prime counting and prime listing up to about ten million.
  • 06 The linear sieve plannedEach composite crossed out exactly once, by its smallest prime factor, with multiplicative functions computed in the same pass.
  • 07 Smallest-prime-factor sieve plannedStore each number's smallest prime factor and factor any number below the limit in logarithmic time. Unlocks problems that factor many numbers.
  • 08 The segmented sieve plannedPrimes in a window [L, R] with R far beyond what fits in memory, using only the primes up to the square root of R.
  • 09 Number and sum of divisors plannedBoth from the prime factorization, listing all divisors, and the harmonic-series sieve that does it for every n at once. Unlocks divisor-counting and perfect-number problems.
  • 10 Prime powers in factorials plannedLegendre's formula for the exponent of p in n!. Unlocks trailing-zero and divisibility-of-factorial problems.

Modular arithmetic

  • 11 Arithmetic mod m plannedCongruences, the remainder of a negative number, which operations survive reduction, and why so many problems use 10^9 + 7.
  • 12 Fast exponentiation plannedSquare-and-multiply, Python's three-argument pow, and matrix powers for linear recurrences. Unlocks huge-exponent and n-th Fibonacci problems.
  • 13 Modular inverses plannedDivision mod m by Fermat's little theorem and by extended Euclid, when an inverse exists, and all inverses of 1..n in linear time.
  • 14 Euler's totient and Euler's theorem plannedCounting the numbers coprime to n, by formula and by sieve, and reducing exponents mod phi(m). Unlocks power towers mod m.
  • 15 Linear congruences plannedSolving a x ≡ b (mod m), how many solutions there are, and when there are none.
  • 16 The Chinese remainder theorem plannedCombining congruences into one, for coprime and non-coprime moduli. Unlocks problems with several periodic conditions.
  • 17 Orders, primitive roots and discrete logarithms plannedThe order of an element, finding a generator, and baby-step giant-step for a^x ≡ b (mod m).

Counting mod p

  • 18 Factorials, inverse factorials and nCr plannedPrecompute factorials and their inverses once, then answer each binomial coefficient in constant time. Unlocks most counting problems with a prime modulus.
  • 19 Binomial identities and Pascal's triangle plannedPascal's rule for composite moduli, stars and bars, and Catalan numbers.
  • 20 Lucas's theorem plannednCr mod a small prime p when n is far larger than p, digit by digit in base p.
  • 21 Inclusion–exclusion plannedCounting by alternating sums over subsets: numbers coprime to n in a range, derangements, surjections.
  • 22 The Möbius function and Möbius inversion plannedInclusion–exclusion over divisors. Unlocks counting coprime pairs and sums of gcds.
  • 23 Divisor blocks: iterating over n // i plannedn // i takes only about 2 sqrt(n) distinct values; summing over blocks of equal value turns many O(n) sums into O(sqrt n).
  • 24 Sums over gcds plannedSums of gcd(i, n) and of gcd(i, j) over a grid, by grouping on the gcd and using the totient and Möbius function.

Large numbers

  • 25 The Miller–Rabin primality test plannedA probabilistic test, and a fixed set of bases that makes it exact for every 64-bit number. Unlocks primality checks up to 10^18.
  • 26 Pollard's rho factorization plannedFactoring 64-bit numbers by finding a cycle in a pseudo-random sequence, with Brent's improvement.
  • 27 Floor sums by a Euclid-like recursion plannedThe sum of floor((a i + b) / m) over a range in logarithmic time, by the same reduction Euclid's algorithm uses. Unlocks lattice-point counting under a line.