Euclid’s algorithm finds gcd(a, b) by repeated remainders. The extended version tracks a little more and gets a powerful bonus: the integers x and y satisfying Bézout’s identitya·x + b·y = gcd(a, b). Those coefficients are the workhorse of number theory — they give modular inverses (the key to RSA decryption and division mod n) and they’re how the Chinese Remainder Theorem stitches congruences together. Step through the coefficient table and watch a·x + b·y = gcd hold at every single row.
O(log min(a,b)) · returns gcd AND x, y with a·x + b·y = gcd · powers modular inverses & CRT
gcd
The greatest common divisor of a and b — the largest integer dividing both.
Bézout identity
There always exist integers x, y with a·x + b·y = gcd(a, b).
the table
Track (r, s, t) so that a·s + b·t = r holds on every row, down to r = gcd.
modular inverse
If gcd(a, m) = 1, then x from a·x + m·y = 1 is a⁻¹ mod m.
extgcd.js — the coefficients come free
Ready
Computing gcd(240, 46) and the Bézout coefficients. We keep a table of (r, s, t) where 240·s + 46·t = r on every row. Each step subtracts q copies of the row above. Step to build it.
–
current r
–
quotient q
✓
identity holds
How it works
Ordinary Euclid replaces (a, b) with (b, a mod b) until the second term is 0; the last nonzero value is the gcd. The extended version carries two extra columns, s and t, initialized so that the first two rows read a = a·1 + b·0 and b = a·0 + b·1. Then every step subtracts q copies of the previous row from the one before it — applied to all three columns at once. Because the same linear combination is applied to r, s, and t together, the invariant a·s + b·t = r is preserved automatically. When r reaches the gcd, that row’s s and t are the Bézout coefficients x and y.
1
Seed two rows
Start with (r=a, s=1, t=0) and (r=b, s=0, t=1). Each already satisfies a·s + b·t = r trivially.
2
Subtract q copies of the previous row
Compute q = ⌊r_prev₂ / r_prev₁⌋ and form a new row = row₂ − q·row₁, applied to r, s, and t together. The remainder r shrinks just like plain Euclid.
3
The identity is preserved
Because the same combination hits all three columns, a·s + b·t = r stays true on the new row. Repeat until r = 0.
✓
Read off gcd and coefficients
The last row with r ≠ 0 gives gcd = r and its s, t are the Bézout coefficients x, y with a·x + b·y = gcd. If gcd = 1, x is the modular inverse of a mod b.
Time
O(log min(a,b))
Returns
gcd + x, y
Invariant
a·s + b·t = r
Powers
inverses, CRT
The code
# extended Euclid: gcd and x, y with a*x + b*y = gcddef extgcd(a, b):
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r # same q applied
old_s, s = s, old_s - q * s # to all three
old_t, t = t, old_t - q * t # columnsreturn old_r, old_s, old_t # gcd, x, y# modular inverse of a mod m (when gcd(a, m) = 1):# g, x, _ = extgcd(a, m); inverse = x % m
Quick check
1. Besides the gcd, what does the extended Euclidean algorithm return?
It returns the Bézout coefficients x and y satisfying a·x + b·y = gcd(a, b). These are what make it useful beyond plain gcd — they give modular inverses and drive the Chinese Remainder Theorem.
2. How do the Bézout coefficients give a modular inverse?
When gcd(a, m) = 1, extended Euclid gives a·x + m·y = 1. Taking this mod m kills the m·y term, leaving a·x ≡ 1 (mod m). So x (reduced mod m) is the modular inverse of a.
3. Why does the invariant a·s + b·t = r stay true through the algorithm?
Each step forms a new row as row₂ − q·row₁ across all three columns simultaneously. Since r, s, and t undergo the identical combination, a·s + b·t = r is preserved on the new row automatically.
FAQ
What is the extended Euclidean algorithm?
An extension of Euclid’s algorithm that computes gcd(a, b) and also integers x, y with a·x + b·y = gcd(a, b) (the Bézout coefficients), in O(log min(a, b)) time by carrying two extra coefficient columns alongside the remainder.
How is it used to find a modular inverse?
To invert a mod m (when gcd(a, m) = 1), run extended Euclid on a and m to get a·x + m·y = 1; reducing mod m gives a·x ≡ 1, so x mod m is the inverse. This underlies modular division and RSA (the private exponent is the inverse of the public one mod φ(n)).
What is the Chinese Remainder Theorem and how does it relate?
CRT says a system x ≡ aᵢ (mod nᵢ) with pairwise-coprime moduli has a unique solution modulo the product of the nᵢ. Building that solution needs modular inverses (invert the product of the other moduli), which come from extended Euclid — so it’s the engine inside CRT.
Where are these used in practice?
Cryptography and computer algebra: RSA key generation and CRT-accelerated decryption (~4× faster), Diffie–Hellman, modular arithmetic libraries, error-correcting codes, and hashing — anywhere you divide modulo a number or combine information across coprime moduli.
The picture: one row per step
The whole table for 240 and 46, one column per row of (r, s, t). Every column satisfies 240·s + 46·t = r. The highlighted column is the last with a nonzero remainder: it carries the gcd 2 and the coefficients x = −9, y = 47. The final column (r = 0) is not wasted: its s and t are 46/2 and −240/2 up to sign, which is the general solution’s step size.
Worked example, step by step
Take a = 240, b = 46. Each row is (r, s, t) with the promise 240·s + 46·t = r. Row 0 and row 1 are the seeds; every later row is the row two above minus q times the row above, where q is the integer quotient of the two remainders. The last column checks the promise by multiplying it out.
Row
q
r
s
t
240·s + 46·t
0
—
240
1
0
240·1 + 46·0 = 240
1
—
46
0
1
240·0 + 46·1 = 46
2
5
10
1
−5
240·1 + 46·(−5) = 10
3
4
6
−4
21
240·(−4) + 46·21 = 6
4
1
4
5
−26
240·5 + 46·(−26) = 4
5
1
2
−9
47
240·(−9) + 46·47 = 2
6
2
0
23
−120
240·23 + 46·(−120) = 0
The remainders 240, 46, 10, 6, 4, 2, 0 are exactly what plain Euclid produces, so the gcd is 2. The two extra columns cost nothing extra: they ride along with the same quotients. The check column never fails, which is the invariant doing its job. Row 5 is the answer, x = −9, y = 47. Notice that the coefficients are not unique: adding 23 to x and subtracting 120 from y (the s and t of the final row, which are 46/2 and 240/2 up to sign) gives another valid pair, and that is why the final row is worth keeping. If the right-hand side were 14 instead of 2, every number in row 5 scales by 7 and 240·(−63) + 46·329 = 14. If it were a number that 2 does not divide, say 15, no integer pair exists.
Complexity and trade-offs
Case
Time
Space
Why
Extended Euclid
O(log min(a, b))
O(1) iterative
Same loop as plain gcd with two more columns. Inverse of 123456 mod 1000000007: 12 iterations.
Worst case for Euclid
O(log min(a, b))
O(1)
Consecutive Fibonacci numbers. For F(90) = 2880067194370816120 and F(89), 88 iterations.
Try every x
O(m)
O(1)
Same inverse by brute force: 78,351,802 trials, against 12.
Fermat: a^(m−2) mod m
O(log m) multiplications
O(1)
About 30 squarings for m = 1000000007 (1000000005 has 30 bits). Works only when m is prime.
Recursive version
O(log min(a, b))
O(log min(a, b)) stack
Same arithmetic, but the call depth equals the iteration count.
The step count depends on the number of digits, not the size of the numbers, so 64-bit inputs finish in under a hundred iterations. The trade against Fermat’s method is generality: Fermat needs a prime modulus and a fast modular exponent, while extended Euclid works for any modulus and tells you when no inverse exists (the gcd is not 1). The trade against recursion is stack depth, which is irrelevant at this size but costs nothing to avoid.
Common mistakes
Using the raw x as the inverse
extgcd(240, 46) returns x = −9. Coefficients can be negative or larger than the modulus. For a = 17, m = 3120 the raw x is −367, not a residue. Always reduce: ((x % m) + m) % m gives 2753. In JavaScript and C, -9 % 46 is −9, so the double reduction is not optional (Python’s % already returns 37).
Not checking that the gcd is 1
extgcd(4, 6) returns gcd 2, x = −1, y = 1. Reading x as an inverse of 4 mod 6 gives 5, and 4·5 mod 6 = 2, not 1. An inverse exists only when the gcd is 1; test g == 1 and report failure otherwise.
Multiplying in floating point
In JavaScript, Number(999999999) * Number(875000006) % 1000000007 evaluates to 999999950 because the 18-digit product exceeds 2⁵³ and loses its low bits. The true value, using BigInt, is 1. Do the multiplication in a wide integer type or with a modular-multiply routine.
Applying CRT to moduli that share a factor
The system x ≡ 1 (mod 4), x ≡ 2 (mod 6) has no solution (a search of 0 to 11 finds none, and the moduli share the factor 2). The standard formula would silently produce a number anyway. Check gcd(n₁, n₂) | (a₁ − a₂) first.
Updating columns with different quotients
Recomputing q from the new remainder before updating s and t breaks the invariant: all three columns must use the same q. With that bug, row 2 of the 240/46 table comes out as r = 10 but s = 1, t = −4, and 240·1 + 46·(−4) = 56, not 10. Compute q once, before any assignment, as the code does.
Where this shows up
RSA key setup
The private exponent is the inverse of the public exponent modulo φ(n). With the textbook primes 61 and 53 (φ = 3120) and public exponent 17, the inverse is 2753. Encrypting 65 gives 2790, and 2790 raised to 2753 mod 3233 returns 65.
Modular division
Dividing by b mod a prime p means multiplying by b⁻¹. Hash-based checksums, combinatorics modulo 1000000007 and finite-field arithmetic all need that inverse for every divisor.
Linear Diophantine equations
ax + by = c has integer solutions exactly when gcd(a, b) divides c. Scale the Bézout pair by c/gcd, as in the 14 = 240·(−63) + 46·329 example above, then add multiples of (b/g, −a/g) for every other solution.
Chinese Remainder Theorem
Combining two congruences with coprime moduli needs the inverse of one modulus modulo the other, which is one call to extended Euclid. Applied repeatedly, it builds a number from its residues.
SOLVE IT YOURSELF
Solve it: gcd, plus the coefficients
The ordinary gcd tells you what the common divisor is. The extended version also hands you the two integers that build it — which is how modular inverses, and therefore RSA, actually work. Write it in Python or TypeScript.
YOUR TASK
Implement extended_gcd(a, b): return (g, x, y) where g is gcd(a, b) and a·x + b·y == g (Bézout’s identity). In TypeScript return a 3-element array.
HINTS — 5 IDEAS
Base case: extended_gcd(a, 0) is (a, 1, 0) — because a·1 + 0·0 == a.
Otherwise recurse on (b, a % b) exactly like the plain Euclidean algorithm, and get back (g, x1, y1).
Now translate those coefficients back one level. Since a % b == a − ⌊a/b⌋·b, substituting gives x = y1 and y = x1 − ⌊a/b⌋·y1.
Use floor division for ⌊a/b⌋ (in TypeScript, Math.floor — plain / gives a fraction and silently breaks the identity).
The payoff: when gcd(a, m) == 1, the x you get back is the modular inverse of a mod m.