Number Theory · Beginner · 8 min read
The Extended Euclidean Algorithm Explained
The Euclidean algorithm is over two thousand years old and is still one of the most useful procedures in mathematics. Its extended form is the engine behind modular inverses, and therefore behind RSA key generation.
The Euclidean algorithm
The idea is that the common divisors of a and b are exactly the common divisors of b and the remainder of a divided by b. So gcd(a, b) = gcd(b, a mod b). Repeat until the remainder is 0; the last non-zero remainder is the greatest common divisor. The numbers shrink quickly, so even 300-digit numbers need only a few hundred steps.
Going backwards: Bézout's identity
Every remainder in the algorithm is a combination of a and b with integer coefficients. Substituting backwards through the division steps expresses the gcd as a·x + b·y. This is Bézout's identity, and the integers x and y are the Bézout coefficients. They are not unique, but any valid pair will do.
Modular inverses
If gcd(a, m) = 1, Bézout gives a·x + m·y = 1. Reducing modulo m, a·x ≡ 1 (mod m), so x is the inverse of a. If the gcd is larger than 1, no inverse exists, since every multiple of a modulo m is divisible by that gcd. Inverses are what make division possible in modular arithmetic.
Speed and common mistakes
The number of division steps grows only with the number of digits: by Lamé's theorem it never exceeds about five times the digit count of the smaller number, and the slowest inputs are consecutive Fibonacci numbers. The most common hand-calculation errors are stopping one step early, dividing in the wrong order (always divide the larger number by the smaller) and losing a sign during back-substitution. Writing the quotients in a table, as the calculator does, makes each of these easy to spot.
Key formulas
gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = |a|a·x + b·y = gcd(a, b) (Bézout)a⁻¹ mod m = x mod m when a·x + m·y = 1
Solved example
Find gcd(240, 46) and write it as 240x + 46y
- Divide repeatedly: 240 = 5·46 + 10; 46 = 4·10 + 6; 10 = 1·6 + 4; 6 = 1·4 + 2; 4 = 2·2 + 0.
- The last non-zero remainder is 2, so gcd(240, 46) = 2.
- Back-substitute: 2 = 6 − 4 = 6 − (10 − 6) = 2·6 − 10 = 2·(46 − 4·10) − 10 = 2·46 − 9·10.
- Replace 10 = 240 − 5·46: 2 = 2·46 − 9·(240 − 5·46) = 47·46 − 9·240.
- So x = −9 and y = 47. Check: 240·(−9) + 46·47 = −2160 + 2162 = 2.
Practice questions
Try each question first, then open the answer.
1. Find gcd(252, 105).
21. Steps: 252 = 2·105 + 42; 105 = 2·42 + 21; 42 = 2·21 + 0.
2. Find the inverse of 7 modulo 40.
23, because 7 · 23 = 161 = 4·40 + 1.
3. Does 6 have an inverse modulo 15?
No. gcd(6, 15) = 3, which is not 1.