Euclid’s Algorithm in Depth
The oldest algorithm: its invariant, Lamé’s bound and the extended GCD.
Euclid's algorithm is about 2,300 years old and still the simplest fast way to compute a greatest common divisor. Its worst case was found in 1844: consecutive Fibonacci numbers, which force about of the input in divisions, and never more than five per decimal digit. This lesson proves that, extends the algorithm to solve , and follows it to a frontier where nobody knows whether gcds can be computed fast in parallel.
What you’ll learn
- Prove Euclid's algorithm correct, with its invariant stated in terms of common divisors.
- Prove Lamé's theorem, that consecutive Fibonacci numbers are the worst case, and derive the bounds and five steps per decimal digit.
- Compute Bézout coefficients with the extended algorithm, prove its invariant, and use them for modular inverses and linear Diophantine equations.
- Compare the bit complexity of Euclid, binary GCD and half-GCD algorithms, and state what is open.
The remainder sequence
Euclid's algorithm computes the gcd of integers , not both zero, by repeating until . Written out, it produces the remainder sequence
with quotients , so that , up to the first . The answer is , and is the number of division steps. (If , the first step only swaps them, with .)
The proof is the one from Correctness: Invariants & Proofs: is an integer combination of and , and is an integer combination of and , so whatever divides one pair divides the other. The bound of steps is wildly pessimistic, and the next step shows by how much.
Think first Euclid's Elements describes the method with repeated subtraction, while . Why does it matter whether you subtract or divide?
One division performs a whole run of subtractions at once, and the quotient counts them. Subtracting, takes a million steps; dividing, it takes one. The subtractive version is still studied (Knuth and Yao analyzed its average behavior in 1975), and its idea returns in binary GCD, where subtraction is cheap and division is avoided.
Lamé’s theorem: Fibonacci is the worst case
Base, : , and gives .
Step, . The first division maps to with , where because the run continues. The run from takes steps, so the induction hypothesis gives
And with , so
Tightness. From , each step uses and walks down the Fibonacci numbers to , then : exactly steps. An exhaustive search confirms that for every the pair with the smallest that needs steps is .
Two corollaries give the bounds people quote. Since for the golden ratio , the inequality gives
And since for , we get , so a smaller number with decimal digits forces : at most five division steps per decimal digit, which is the form of Lamé's theorem usually stated.
How many division steps does Euclid's algorithm make on ?
Show the answer
28
takes exactly steps, so . By Lamé's theorem, no pair whose smaller number is below needs that many.
Extended Euclid and Bézout’s identity
Run the remainder sequence with bookkeeping and you get more than the gcd. Next to each remainder , keep integers with . They start as for and for , and follow the same recurrence as the remainders. This is the extended Euclidean algorithm:
def ext_gcd(a, b): # a, b >= 0, not both 0
x0, y0, x1, y1 = 1, 0, 0, 1
r0, r1 = a, b
while r1 != 0:
# invariant: a*x0 + b*y0 == r0 and a*x1 + b*y1 == r1
q = r0 // r1
r0, r1 = r1, r0 - q * r1
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return r0, x0, y0 # a*x0 + b*y0 == r0 == gcd(a, b)ext_gcd(240, 46) returns : . When neither input divides the other, the coefficients stay small: and , where is the gcd.
Initialization.
Maintenance. Subtract times row from row ; a linear combination of true equations is true:
Exit. When , row reads . Minimality: every combination is a multiple of every common divisor, included, so no positive combination is smaller.
Two applications run all of modular arithmetic:
- Modular inverses. If , then gives , so is the inverse of . For and ,
ext_gcd(7, 26)returns , and : indeed . Python computes it directly aspow(7, -1, 26). - Linear Diophantine equations. has integer solutions if and only if divides . Then gives the solution , and all solutions are for integers .
Which of these equations has integer solutions?
Show the answer
B.
divides 8. ext_gcd(6, 10) gives , so is a solution, and so is every .
Faster gcds, and an open question
For numbers that fit in a machine word, Euclid's algorithm with hardware division is hard to beat. For long numbers the right cost is the number of bit operations on inputs of bits:
- Euclid with schoolbook division costs in total, not , because the lengths of the quotients add up to at most about ; the proof is in Models of Computation.
- Binary GCD (Stein, 1967) avoids division altogether and uses only shifts, subtractions and parity tests. It also costs .
- Lehmer's method (1938) runs most steps on the leading digits only, in single-precision arithmetic, and applies them to the full numbers in batches: the same with a much smaller constant.
- Half-GCD (Knuth, 1970; Schönhage, 1971) splits the remainder sequence recursively, the way fast multiplication splits products, and runs in , where is the cost of multiplying -bit numbers. With (Harvey & van der Hoeven, 2021) that is . Big-number libraries such as GMP switch to subquadratic gcd for very large inputs.
def binary_gcd(a, b): # a, b >= 0
if a == 0 or b == 0:
return a | b
shift = ((a | b) & -(a | b)).bit_length() - 1 # common factors of 2
a >>= (a & -a).bit_length() - 1 # make a odd
while b:
b >>= (b & -b).bit_length() - 1 # make b odd
if a > b:
a, b = b, a
b -= a # odd - odd is even
return a << shiftStein's rules: ; for odd ; and for odd , where is even. x & -x isolates the lowest set bit, so each shift strips every factor of 2 at once. Checked against math.gcd on 200,000 random pairs.
Key takeaways
- Euclid's algorithm keeps the set of common divisors unchanged, , and stops because the second number strictly decreases.
- Lamé (1844): division steps on force and , so consecutive Fibonacci numbers are the worst case, , and there are at most five steps per decimal digit; on average there are about .
- The extended algorithm keeps and ends with Bézout coefficients, which give modular inverses and all solutions of when divides .
- On -bit numbers, Euclid and binary GCD cost bit operations and half-GCD ; whether gcd is in NC is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which pair , with the smallest possible , makes Euclid's algorithm take 10 division steps?
Show the answer
B.
By Lamé's theorem, steps need , and takes exactly 10 steps.
Which invariant does the extended Euclidean algorithm maintain for each remainder ?
- divides both and
- and are both positive
Show the answer
C.
It holds for and by the choice of starting rows, and each new row is the old row minus times the current one, exactly as for the remainders. At the end it gives .
What is the inverse of 3 modulo 11?
- 4
- 3
- 8
- It does not exist
Show the answer
A. 4
. It exists because , and the extended algorithm finds .
Euclid's algorithm on two -bit numbers makes divisions of -bit numbers. Why is its bit complexity and not ?
- Because each division costs
- Because the numbers halve at every step
- It is
- Because a division with a -bit quotient costs , and the quotient lengths add up to at most about
Show the answer
D. Because a division with a -bit quotient costs , and the quotient lengths add up to at most about
Long quotients are expensive but rare: the product of all quotients is at most , so their lengths total at most , plus one per step. The whole run costs .
Further reading
- D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. (Addison-Wesley, 1997), §4.5.2–4.5.3.
- G. Lamé, "Note sur la limite du nombre des divisions dans la recherche du plus grand commun diviseur entre deux nombres entiers," Comptes Rendus de l'Académie des Sciences 19 (1844).
- J. Stein, "Computational problems associated with Racah algebra," Journal of Computational Physics 1(3) (1967).
- N. Möller, "On Schönhage's algorithm and subquadratic integer GCD computation," Mathematics of Computation 77 (2008).