man number-theory/gcd
lesson 1 of 27 · Divisibility and the Euclidean algorithm
GCD, Euclid, and Bézout
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 in at most 90 (91 if the smaller one comes first). This lesson proves why, extends the algorithm to find and with , and uses that to solve equations like 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 .
In general, divides , written , when for some integer . The greatest common divisor is the largest that divides both. Every divides 0, so , and 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 and , then divides every integer combination of them:
Proof: and , so .
Euclid’s step
Divide 1071 by 462: . Any number dividing 1071 and 462 also divides , by the fact above. Any number dividing 462 and 147 also divides . 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 , write with
(in Python, q, r = divmod(a, b)). Since , a common divisor of
and divides , and a common divisor of and divides
. The two pairs share all their common divisors, so
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 , the first step only swaps them: . 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.
A 75 by 27 rectangle cut into squares: two of side 27, one of side 21, three of side 6, two of side 3. (This figure steps through a recorded run; it needs JavaScript.)
Euclid on 75 and 27: four division steps, gcd 3. Each step cuts squares of side 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:
A 34 by 21 rectangle cut into one square each of side 21, 13, 8, 5, 3, 2, and two of side 1. (This figure steps through a recorded run; it needs JavaScript.)
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 and .
Theorem (Lamé). If and Euclid’s algorithm takes division steps on , then and .
Proof, by induction on . For : , and gives . For : the first step is . Another step follows, so , and the pair with takes steps. By induction and . Since , , so
The bound is exact: on every step is until , which is steps. A search over all confirms that is the pair with the smallest for each 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 , the positive root of . By induction, for : it holds for and , and
So , which gives the two usual forms of the bound. If has decimal digits, then , because . Hence :
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. , so for the theorem allows at most steps, and the pair takes exactly 90. For the largest Fibonacci number is , so at most 85 steps. Each step is one division, so Euclid’s algorithm costs divisions.
Extended Euclid and Bézout’s identity
Run Euclid on 240 and 46, but keep, next to each remainder , two integers with . The first two rows are free: and . Each new row is the row two above minus times the row above, the same operation Euclid applies to the remainders:
| q | r | x | y |
|---|---|---|---|
| 240 | 1 | 0 | |
| 46 | 0 | 1 | |
| 5 | 10 | 1 | -5 |
| 4 | 6 | -4 | 21 |
| 1 | 4 | 5 | -26 |
| 1 | 2 | -9 | 47 |
| 2 | 0 | 23 | -120 |
The last nonzero remainder is , and its row says .
Why every row is correct: if and , subtracting times the second from the first gives
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 there are integers with
(For negative or , flip the sign of or ; for , any work.) Two consequences are used constantly:
- The values of are exactly the multiples of . Every value is a multiple of , because divides and . Every multiple is a value: take . In particular is the smallest positive value of , and every common divisor of and divides .
- Euclid’s lemma. If and , then . From , , and 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 , so negative inputs need no
special case except the sign of the result. How big do and get? For
the tests find and
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 and fit in a long long, so do and .
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 . Note . That holds in general:
Proof for . Let and write , . Then : a common divisor of and makes a common divisor of and , so . The number is a multiple of both. Any common multiple is , and means , so by Euclid’s lemma and is a multiple of . So the least one is .
The formula has a trap in C++: can overflow while the lcm fits. With
and , both fit in a long long, and so
does the lcm, . But is larger
than . 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
gcdand makeslcm0, and the empty cases return the identity of each operation (0 for gcd, 1 for lcm). - For a list,
math.gcd(*nums)does whatreduce(math.gcd, nums)does. Several arguments are accepted since Python 3.9, whenmath.lcmwas also added (per the documentation). - In 3.15 both functions live in the new
math.integermodule. The names inmathare 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 % 3is 2) and C++’s takes the sign of the dividend (-7 % 3is -1). A C++ gcd should take absolute values first, or usestd::gcd, which returns the gcd of the absolute values.
Solving ax + by = c
Which pairs of integers satisfy ? And ? The second has none: the left side is always even. In general, by the first consequence of Bézout, takes exactly the multiples of , so
To find one, scale Bézout’s by . To find all of them, take two solutions and . Subtracting, ; dividing by , with . By Euclid’s lemma , so , and then . Every such pair is a solution, so the solutions are exactly
The function returns one solution and the two steps, with 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 , , and the non-negative solutions are to 3. Problems that ask for non-negative or bounded solutions reduce to finding the range of from these two linear expressions. The test compares the function with a brute-force search for every from -6 to 6 and 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.
- LeetCode 1979. Find Greatest Common Divisor of Array: one call to
gcd. - LeetCode 914. X of a Kind in a Deck of Cards: the gcd of a list of counts.
- LeetCode 1071. Greatest Common Divisor of Strings: the answer’s length can only be the gcd of the two lengths.
- LeetCode 2413. Smallest Even Multiple: an lcm.
- LeetCode 365. Water and Jug Problem: Bézout; the reachable amounts are the multiples of the gcd, within capacity.
- LeetCode 1250. Check If It Is a Good Array: Bézout for many numbers; the answer depends only on the gcd of all of them.
- LeetCode 878. Nth Magical Number: count multiples of either number below a bound with the lcm, then binary search.
- LeetCode 2447. Number of Subarrays With GCD Equal to K: running gcds over subarrays (lesson 3 makes it faster).
- Codeforces 1458A. Row GCD: Euclid’s step in the form , applied to a whole list.
- Codeforces 7C. Line: extended Euclid, with the solvability test .
- Codeforces 1244C. The Football Season: a linear equation in two unknowns that needs a non-negative solution with a bounded sum; use the general solution.
Try it yourself
- Compute by hand. How many division steps does it take?
- Find integers with , then all of them.
- What is the smallest (with ) for which Euclid’s algorithm takes 12 division steps?
- How many pairs of non-negative integers satisfy ? And ?
- What is ? What is the largest for which fits in a signed 64-bit integer?
- Prove that . Hint: show that , and compare with Euclid’s step on .
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
- 37, in five steps: the quotients are 1, 2, 2, 2, 2 and the remainders 444, 185, 74, 37, 0. ( and .)
- Extended Euclid gives , . All solutions: , .
- , with , as Lamé’s theorem predicts.
- 17 pairs, from to : , for to 16. None for 701, since does not divide 701.
- The largest is 42: , and multiplying in 43 gives 9419588158802421600, which exceeds .
- Write . Then , and divides , while . So one Euclid step on gives , mirroring the step . It ends at . The tests check the identity for all .
Sources
- Euclid, Elements, Book VII, Proposition 1 and Proposition 2, in D. E. Joyce’s online edition. Euclid’s version subtracts repeatedly instead of dividing.
- Wikipedia, Euclidean algorithm, sections “Number of steps” and “Worst-case”: Lamé’s 1844 bound of five steps per decimal digit, and the Fibonacci worst case in the indexing used here (, ).
- Wikipedia, Bézout’s identity: the statement, and that the values of are exactly the multiples of the gcd.
- cp-algorithms: Euclidean algorithm (Lamé’s theorem, stated with a bound on , and the divide-first lcm), Extended Euclidean Algorithm, Linear Diophantine Equations.
- Python documentation: math.integer (
gcdandlcm, new in 3.15) and math (the aliases and the 3.9 version notes). - cppreference: std::gcd and std::lcm.
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.