man number-theory/gcd

lesson 1 of 27 · Divisibility and the Euclidean algorithm

GCD, Euclid, and Bézout

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-01

What is the largest number that divides both 1071 and 462? Listing divisors works for small numbers and fails at 18 digits. Euclid’s algorithm answers it in three divisions, and for any two numbers below 2632^{63} in at most 90 (91 if the smaller one comes first). This lesson proves why, extends the algorithm to find xx and yy with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b), and uses that to solve equations like 6x+10y=1006x + 10y = 100 in integers.

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

Divisors and the gcd

The divisors of 12 are 1, 2, 3, 4, 6, 12. The divisors of 18 are 1, 2, 3, 6, 9, 18. The common ones are 1, 2, 3, 6, and the greatest is 6, so gcd⁡(12,18)=6\gcd(12, 18) = 6.

In general, dd divides aa, written d∣ad \mid a, when a=kda = kd for some integer kk. The greatest common divisor gcd⁡(a,b)\gcd(a, b) is the largest dd that divides both. Every dd divides 0, so gcd⁡(a,0)=∣a∣\gcd(a, 0) = \lvert a\rvert, and gcd⁡(0,0)=0\gcd(0, 0) = 0 by convention: there is no largest divisor of 0, and 0 is the value that keeps the identities below true.

One fact does most of the work in this lesson. If d∣ad \mid a and d∣bd \mid b, then dd divides every integer combination of them:

d∣a and d∣b  ⟹  d∣ax+byfor all integers x,y.d \mid a \text{ and } d \mid b \implies d \mid ax + by \quad \text{for all integers } x, y.

Proof: a=d a′a = d\,a' and b=d b′b = d\,b', so ax+by=d(a′x+b′y)ax + by = d(a'x + b'y).

Euclid’s step

Divide 1071 by 462: 1071=2⋅462+1471071 = 2 \cdot 462 + 147. Any number dividing 1071 and 462 also divides 147=1071−2⋅462147 = 1071 - 2 \cdot 462, by the fact above. Any number dividing 462 and 147 also divides 1071=2⋅462+1471071 = 2 \cdot 462 + 147. So the pairs (1071, 462) and (462, 147) have exactly the same common divisors, and therefore the same greatest one. Repeat:

1071 = 2*462 + 147
462 = 3*147 + 21
147 = 7*21 + 0
gcd(1071, 462) = 21, 3 division steps

The general step: for b>0b > 0, write a=qb+ra = qb + r with 0≤r<b0 \le r < b (in Python, q, r = divmod(a, b)). Since r=a−qbr = a - qb, a common divisor of aa and bb divides rr, and a common divisor of bb and rr divides a=qb+ra = qb + r. The two pairs share all their common divisors, so

gcd⁡(a,b)=gcd⁡(b, a mod b),gcd⁡(a,0)=a.\gcd(a, b) = \gcd(b,\ a \bmod b), \qquad \gcd(a, 0) = a.

The second number strictly decreases and stays non-negative, so it reaches 0, and then the first number is the answer. In code:

def gcd(a, b):
    """Greatest common divisor by Euclid's algorithm, iterative."""
    a, b = abs(a), abs(b)
    while b:
        a, b = b, a % b
    return a

The abs makes negative inputs behave like math.gcd: the result is never negative. Without it, Python’s %, which takes the sign of the divisor, can leave a negative number at the end: the same loop on 12 and -18 returns -6.

If a<ba < b, the first step only swaps them: 27=0⋅75+2727 = 0 \cdot 75 + 27. That costs one extra step and nothing else.

Euclid as cutting squares

The same steps have a picture. Take a 75 by 27 rectangle. Cut off as many 27 by 27 squares as fit, and a 21 by 27 rectangle is left. Cut squares off that one, and so on. Each cut is one division: the quotient is how many squares fit, the remainder is the short side of what is left. The last squares fill their rectangle exactly, and their side is the gcd. That is also the largest square that tiles the whole rectangle: its side must divide 75 and 27.

Euclid on 75 and 27: four division steps, gcd 3. Each step cuts qq squares of side bb off the rectangle that is left. Trace from python3 -m cpmath.euclid_trace 75 27 in cp-math.

How many steps: Lamé’s theorem

Some pairs take many steps for their size. Here is 34 and 21:

Euclid on 34 and 21: seven steps, every quotient 1 except the last. Trace from python3 -m cpmath.euclid_trace 34 21 in cp-math.

Every quotient is 1 except the last, so each step removes as little as possible, and the sides shrink through the Fibonacci numbers 34, 21, 13, 8, 5, 3, 2, 1. These are the worst inputs. Write F1=F2=1F_1 = F_2 = 1 and Fk=Fk−1+Fk−2F_{k} = F_{k-1} + F_{k-2}.

Theorem (Lamé). If a>b≥1a > b \ge 1 and Euclid’s algorithm takes nn division steps on (a,b)(a, b), then a≥Fn+2a \ge F_{n+2} and b≥Fn+1b \ge F_{n+1}.

Proof, by induction on nn. For n=1n = 1: b≥1=F2b \ge 1 = F_2, and a>ba > b gives a≥2=F3a \ge 2 = F_3. For n≥2n \ge 2: the first step is a=qb+ra = qb + r. Another step follows, so r≥1r \ge 1, and the pair (b,r)(b, r) with b>r≥1b > r \ge 1 takes n−1n - 1 steps. By induction b≥Fn+1b \ge F_{n+1} and r≥Fnr \ge F_n. Since a>ba > b, q≥1q \ge 1, so

a=qb+r≥b+r≥Fn+1+Fn=Fn+2.■a = qb + r \ge b + r \ge F_{n+1} + F_n = F_{n+2}. \qquad \blacksquare

The bound is exact: on (Fn+2,Fn+1)(F_{n+2}, F_{n+1}) every step is Fk+1=1⋅Fk+Fk−1F_{k+1} = 1 \cdot F_k + F_{k-1} until F3=2=2⋅F2+0F_3 = 2 = 2 \cdot F_2 + 0, which is nn steps. A search over all a<1000a < 1000 confirms that (Fn+2,Fn+1)(F_{n+2}, F_{n+1}) is the pair with the smallest aa for each nn up to 10: (2, 1), (3, 2), (5, 3), …, (144, 89).

To turn this into a count, compare Fibonacci numbers with powers of the golden ratio φ=(1+5)/2≈1.618\varphi = (1 + \sqrt 5)/2 \approx 1.618, the positive root of φ2=φ+1\varphi^2 = \varphi + 1. By induction, Fk≥φk−2F_k \ge \varphi^{k-2} for k≥1k \ge 1: it holds for F1=1≥φ−1F_1 = 1 \ge \varphi^{-1} and F2=1=φ0F_2 = 1 = \varphi^0, and

Fk=Fk−1+Fk−2≥φk−3+φk−4=φk−4(φ+1)=φk−2.F_k = F_{k-1} + F_{k-2} \ge \varphi^{k-3} + \varphi^{k-4} = \varphi^{k-4}(\varphi + 1) = \varphi^{k-2}.

So b≥Fn+1≥φn−1b \ge F_{n+1} \ge \varphi^{n-1}, which gives the two usual forms of the bound. If bb has dd decimal digits, then b<10d<φ5db < 10^d < \varphi^{5d}, because φ5≈11.09>10\varphi^5 \approx 11.09 > 10. Hence n−1<5dn - 1 < 5d:

n≤1+log⁡φb,n≤5d.n \le 1 + \log_\varphi b, \qquad n \le 5d.

The second is the form Lamé published in 1844: at most five steps per decimal digit of the smaller number. For contest limits, the exact Fibonacci bound is sharper than either. F92=7540113804746346429<263≤F93F_{92} = 7540113804746346429 < 2^{63} \le F_{93}, so for a<263a < 2^{63} the theorem allows at most n=90n = 90 steps, and the pair (F92,F91)(F_{92}, F_{91}) takes exactly 90. For a≤1018a \le 10^{18} the largest Fibonacci number is F87F_{87}, so at most 85 steps. Each step is one division, so Euclid’s algorithm costs O(log⁡min⁡(a,b))O(\log \min(a, b)) divisions.

Extended Euclid and Bézout’s identity

Run Euclid on 240 and 46, but keep, next to each remainder rr, two integers x,yx, y with 240x+46y=r240x + 46y = r. The first two rows are free: 240=240⋅1+46⋅0240 = 240 \cdot 1 + 46 \cdot 0 and 46=240⋅0+46⋅146 = 240 \cdot 0 + 46 \cdot 1. Each new row is the row two above minus qq times the row above, the same operation Euclid applies to the remainders:

qrxy
24010
4601
5101-5
46-421
145-26
12-947
2023-120

The last nonzero remainder is gcd⁡(240,46)=2\gcd(240, 46) = 2, and its row says 240⋅(−9)+46⋅47=2240 \cdot (-9) + 46 \cdot 47 = 2.

Why every row is correct: if ax1+by1=r1ax_1 + by_1 = r_1 and ax2+by2=r2ax_2 + by_2 = r_2, subtracting qq times the second from the first gives

a(x1−qx2)+b(y1−qy2)=r1−qr2=r3.a(x_1 - qx_2) + b(y_1 - qy_2) = r_1 - qr_2 = r_3.

The first two rows hold, so every row holds, including the one with the gcd. This proves the theorem:

Bézout’s identity. For integers a,ba, b there are integers x,yx, y with

ax+by=gcd⁡(a,b).ax + by = \gcd(a, b).

(For negative aa or bb, flip the sign of xx or yy; for a=b=0a = b = 0, any x,yx, y work.) Two consequences are used constantly:

  1. The values of ax+byax + by are exactly the multiples of g=gcd⁡(a,b)g = \gcd(a, b). Every value is a multiple of gg, because gg divides aa and bb. Every multiple mgmg is a value: take mx,mymx, my. In particular gg is the smallest positive value of ax+byax + by, and every common divisor of aa and bb divides gg.
  2. Euclid’s lemma. If gcd⁡(a,b)=1\gcd(a, b) = 1 and b∣akb \mid ak, then b∣kb \mid k. From ax+by=1ax + by = 1, k=akx+bkyk = akx + bky, and bb divides both terms.

The iterative version keeps only the last two rows:

def ext_gcd(a, b):
    """Return (g, x, y) with a*x + b*y == g == gcd(a, b) and g >= 0.

    Keeps two rows (r, x, y) with a*x + b*y == r and replaces the older one
    by older - q*newer, which is the remainder step of Euclid applied to the
    whole row.
    """
    old_r, r = a, b
    old_x, x = 1, 0
    old_y, y = 0, 1
    while r:
        q = old_r // r
        old_r, r = r, old_r - q * r
        old_x, x = x, old_x - q * x
        old_y, y = y, old_y - q * y
    if old_r < 0:  # possible only when an input is negative
        old_r, old_x, old_y = -old_r, -old_x, -old_y
    return old_r, old_x, old_y
ext_gcd(240, 46) = (2, -9, 47)
ext_gcd(1071, 462) = (21, -3, 7)
ext_gcd(-240, 46) = (2, 9, 47)

The row argument holds for any integer qq, so negative inputs need no special case except the sign of the result. How big do xx and yy get? For a,b≥1a, b \ge 1 the tests find ∣x∣≤b/g\lvert x\rvert \le b/g and ∣y∣≤a/g\lvert y\rvert \le a/g on every pair below 150 and on 5,000 random pairs of up to 100 bits. I have not proved it here, but it is what makes the C++ version safe: if aa and bb fit in a long long, so do xx and yy.

lcm, and the order that avoids overflow

The multiples of 4 are 4, 8, 12, 16, 20, 24, …, those of 6 are 6, 12, 18, 24, …, and the least common one is lcm⁡(4,6)=12\operatorname{lcm}(4, 6) = 12. Note gcd⁡(4,6)⋅lcm⁡(4,6)=2⋅12=24=4⋅6\gcd(4, 6) \cdot \operatorname{lcm}(4, 6) = 2 \cdot 12 = 24 = 4 \cdot 6. That holds in general:

lcm⁡(a,b)=∣ab∣gcd⁡(a,b)(a,b≠0).\operatorname{lcm}(a, b) = \frac{\lvert ab\rvert}{\gcd(a, b)} \qquad (a, b \ne 0).

Proof for a,b>0a, b > 0. Let g=gcd⁡(a,b)g = \gcd(a, b) and write a=ga′a = ga', b=gb′b = gb'. Then gcd⁡(a′,b′)=1\gcd(a', b') = 1: a common divisor dd of a′a' and b′b' makes dgdg a common divisor of aa and bb, so d=1d = 1. The number ga′b′=ab′=a′bga'b' = ab' = a'b is a multiple of both. Any common multiple MM is M=ak=ga′kM = ak = ga'k, and b∣Mb \mid M means b′∣a′kb' \mid a'k, so b′∣kb' \mid k by Euclid’s lemma and MM is a multiple of ga′b′ga'b'. So the least one is ga′b′=ab/gga'b' = ab/g. ■\blacksquare

The formula has a trap in C++: abab can overflow while the lcm fits. With a=3⋅109a = 3 \cdot 10^9 and b=4⋅109b = 4 \cdot 10^9, both fit in a long long, and so does the lcm, 1.2⋅10101.2 \cdot 10^{10}. But ab=1.2⋅1019ab = 1.2 \cdot 10^{19} is larger than 263−1=92233720368547758072^{63} - 1 = 9223372036854775807. Dividing first, a / g * b, keeps every intermediate value at most the result. The cp-math repo has this as demos/lcm_overflow.cpp; built with Apple clang 21 and -fsanitize=undefined, it prints:

demos/lcm_overflow.cpp:14:23: runtime error: signed integer overflow: 3000000000 * 4000000000 cannot be represented in type 'long long'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior demos/lcm_overflow.cpp:14:23
gcd = 1000000000
a / g * b = 12000000000
a * b / g = -6446744073
-7 % 3 = -1, -7 / 3 = -2
std::gcd(-12, 18) = 6, std::lcm(-4, 6) = 12

Without the sanitizer (I tried -O0 and -O2) it prints the same wrong number and no warning. Signed overflow is undefined behaviour, so another compiler may print something else. Python’s integers do not overflow, so a * b // g is correct there, but the cp-math version divides first anyway so that it ports as is:

def lcm(a, b):
    """Least common multiple. Divides before it multiplies, so in a
    fixed-width language the intermediate value never exceeds the result."""
    if a == 0 or b == 0:
        return 0
    return abs(a // gcd(a, b) * b)

In C++, std::lcm (C++17, <numeric>) has undefined behaviour when the result does not fit, according to cppreference; dividing first does not help when the lcm itself is too large. The lcm of 1 to 42 fits in 63 bits, and the lcm of 1 to 43 does not.

In Python: math.gcd and math.lcm

Both are built-in functions (builtin_function_or_method, so written in C), and both accept any number of arguments. Recorded with Python 3.15.2:

math.gcd(12, 18) -> 6
math.gcd(-12, 18) -> 6
math.gcd(0, -5) -> 5
math.gcd(0, 0) -> 0
math.gcd() -> 0
math.gcd(12, 18, 27) -> 3
math.lcm(-4, 6) -> 12
math.lcm(0, 5) -> 0
math.lcm() -> 1
math.lcm(4, 6, 10) -> 60
math.gcd is math.integer.gcd -> True  math.lcm is math.integer.lcm -> True
math.gcd(2.0, 4) -> TypeError: 'float' object cannot be interpreted as an integer
-7 % 3 -> 2  -7 // 3 -> -3
reduce(math.gcd, [84, 126, 210]) -> 42  math.gcd(*[84, 126, 210]) -> 42

What to take from it:

  • The result is never negative, a zero argument is ignored by gcd and makes lcm 0, and the empty cases return the identity of each operation (0 for gcd, 1 for lcm).
  • For a list, math.gcd(*nums) does what reduce(math.gcd, nums) does. Several arguments are accepted since Python 3.9, when math.lcm was also added (per the documentation).
  • In 3.15 both functions live in the new math.integer module. The names in math are the same objects, kept for compatibility. The documentation marks them soft deprecated; with warnings turned into errors, calling them still raises nothing.
  • Floats are rejected, even integral ones. Convert with int() first.
  • Python’s % takes the sign of the divisor (-7 % 3 is 2) and C++’s takes the sign of the dividend (-7 % 3 is -1). A C++ gcd should take absolute values first, or use std::gcd, which returns the gcd of the absolute values.

Solving ax + by = c

Which pairs of integers satisfy 6x+10y=1006x + 10y = 100? And 6x+10y=76x + 10y = 7? The second has none: the left side is always even. In general, by the first consequence of Bézout, ax+byax + by takes exactly the multiples of g=gcd⁡(a,b)g = \gcd(a, b), so

ax+by=c has an integer solution  ⟺  g∣c.ax + by = c \text{ has an integer solution} \iff g \mid c.

To find one, scale Bézout’s x,yx, y by c/gc/g. To find all of them, take two solutions (x0,y0)(x_0, y_0) and (x,y)(x, y). Subtracting, a(x−x0)=−b(y−y0)a(x - x_0) = -b(y - y_0); dividing by gg, a′(x−x0)=−b′(y−y0)a'(x - x_0) = -b'(y - y_0) with gcd⁡(a′,b′)=1\gcd(a', b') = 1. By Euclid’s lemma b′∣x−x0b' \mid x - x_0, so x=x0+kb′x = x_0 + kb', and then y=y0−ka′y = y_0 - ka'. Every such pair is a solution, so the solutions are exactly

x=x0+k bg,y=y0−k ag,k∈Z.x = x_0 + k\,\frac{b}{g}, \qquad y = y_0 - k\,\frac{a}{g}, \qquad k \in \mathbb{Z}.

The function returns one solution and the two steps, with x0x_0 moved to the smallest non-negative value:

def solve_linear(a, b, c):
    """All integer solutions of a*x + b*y == c, for (a, b) != (0, 0).

    Returns None when there are none. Otherwise (x0, y0, dx, dy): the
    solutions are exactly x = x0 + k*dx, y = y0 - k*dy for integer k, with
    dx = b // g and dy = a // g. When b != 0, x0 is the smallest solution
    x >= 0 (0 <= x0 < |dx|).
    """
    if a == 0 and b == 0:
        raise ValueError("a and b are both 0")
    g, x, y = ext_gcd(a, b)
    if c % g:
        return None
    k = c // g
    x0, y0 = x * k, y * k
    dx, dy = b // g, a // g
    if dx:
        # move k = t steps along the solutions so that x0 lands in [0, |dx|)
        t = (x0 - x0 % abs(dx)) // dx
        x0, y0 = x0 - t * dx, y0 + t * dy
    return x0, y0, dx, dy
solve_linear(6, 10, 100) = (0, 10, 5, 3)
solve_linear(6, 10, 7) = None
nonnegative solutions: [(0, 10), (5, 7), (10, 4), (15, 1)]

So x=5kx = 5k, y=10−3ky = 10 - 3k, and the non-negative solutions are k=0k = 0 to 3. Problems that ask for non-negative or bounded solutions reduce to finding the range of kk from these two linear expressions. The test compares the function with a brute-force search for every a,ba, b from -6 to 6 and cc from -12 to 12.

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. Compute gcd⁡(1517,1073)\gcd(1517, 1073) by hand. How many division steps does it take?
  2. Find integers x,yx, y with 1517x+1073y=gcd⁡(1517,1073)1517x + 1073y = \gcd(1517, 1073), then all of them.
  3. What is the smallest aa (with a>b≥1a > b \ge 1) for which Euclid’s algorithm takes 12 division steps?
  4. How many pairs of non-negative integers satisfy 14x+21y=70014x + 21y = 700? And 14x+21y=70114x + 21y = 701?
  5. What is lcm⁡(1,2,…,20)\operatorname{lcm}(1, 2, \dots, 20)? What is the largest nn for which lcm⁡(1,…,n)\operatorname{lcm}(1, \dots, n) fits in a signed 64-bit integer?
  6. Prove that gcd⁡(2m−1,2n−1)=2gcd⁡(m,n)−1\gcd(2^m - 1, 2^n - 1) = 2^{\gcd(m, n)} - 1. Hint: show that (2m−1) mod (2n−1)=2m mod n−1(2^m - 1) \bmod (2^n - 1) = 2^{m \bmod n} - 1, and compare with Euclid’s step on (m,n)(m, n).

Answers

Each one is asserted in tests/test_lesson01.py, by a check that does not use the function the exercise is about where that is possible (brute-force searches, direct divisibility checks).

Show the answers
  1. 37, in five steps: the quotients are 1, 2, 2, 2, 2 and the remainders 444, 185, 74, 37, 0. (1517=37⋅411517 = 37 \cdot 41 and 1073=37⋅291073 = 37 \cdot 29.)
  2. Extended Euclid gives x=−12x = -12, y=17y = 17. All solutions: x=−12+29kx = -12 + 29k, y=17−41ky = 17 - 41k.
  3. a=377=F14a = 377 = F_{14}, with b=233=F13b = 233 = F_{13}, as Lamé’s theorem predicts.
  4. 17 pairs, from (2,32)(2, 32) to (50,0)(50, 0): x=2+3kx = 2 + 3k, y=32−2ky = 32 - 2k for k=0k = 0 to 16. None for 701, since gcd⁡(14,21)=7\gcd(14, 21) = 7 does not divide 701.
    1. The largest nn is 42: lcm⁡(1,…,42)=219060189739591200\operatorname{lcm}(1, \dots, 42) = 219060189739591200, and multiplying in 43 gives 9419588158802421600, which exceeds 263−12^{63} - 1.
  5. Write m=qn+rm = qn + r. Then 2m−1=2r(2qn−1)+(2r−1)2^m - 1 = 2^r(2^{qn} - 1) + (2^r - 1), and 2n−12^n - 1 divides 2qn−12^{qn} - 1, while 2r−1<2n−12^r - 1 < 2^n - 1. So one Euclid step on (2m−1,2n−1)(2^m - 1, 2^n - 1) gives (2n−1,2r−1)(2^n - 1, 2^r - 1), mirroring the step (m,n)→(n,r)(m, n) \to (n, r). It ends at (2gcd⁡(m,n)−1,20−1=0)(2^{\gcd(m,n)} - 1, 2^0 - 1 = 0). The tests check the identity for all m,n≤60m, n \le 60.

Sources

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.