TExcelTAD
Home › Number Theory & Cryptography › The Extended Euclidean Algorithm

The Extended Euclidean Algorithm

Euclid's algorithm tells you that gcd⁡(a,b)=1\gcd(a, b) = 1. The extended version also tells you why: it finds integers xx and yy with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b). Those coefficients are modular inverses, which RSA, Diffie-Hellman, elliptic curves and the Chinese remainder theorem all need.

Bézout's identity

For integers a,ba, b, not both 0, there are integers x,yx, y with

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

Moreover gcd⁡(a,b)\gcd(a, b) is the smallest positive integer of the form ax+byax + by. (Sketch: let dd be that smallest positive value. Dividing aa by dd leaves a remainder that is again of the form ax+byax + by and smaller than dd, so it is 0; hence d∣ad \mid a and likewise d∣bd \mid b. Any common divisor of aa and bb divides dd, so dd is the greatest.)

A corollary used constantly: aa and bb are coprime if and only if ax+by=1ax + by = 1 has a solution.

Back-substitution by hand

Run Euclid on 240240 and 4646, then walk back up, writing each remainder as a combination of 240240 and 4646:

240=5⋅46+1010=240−5⋅4646=4⋅10+66=46−4⋅10=−4⋅240+21⋅4610=1⋅6+44=10−6=5⋅240−26⋅466=1⋅4+22=6−4=−9⋅240+47⋅46\begin{aligned} 240 &= 5 \cdot 46 + 10 && 10 = 240 - 5 \cdot 46 \\ 46 &= 4 \cdot 10 + 6 && 6 = 46 - 4 \cdot 10 = -4 \cdot 240 + 21 \cdot 46 \\ 10 &= 1 \cdot 6 + 4 && 4 = 10 - 6 = 5 \cdot 240 - 26 \cdot 46 \\ 6 &= 1 \cdot 4 + 2 && 2 = 6 - 4 = -9 \cdot 240 + 47 \cdot 46 \end{aligned}

So gcd⁡(240,46)=2=240⋅(−9)+46⋅47\gcd(240, 46) = 2 = 240 \cdot (-9) + 46 \cdot 47.

The iterative algorithm

Instead of walking back, keep the coefficients alongside the remainders. Each row (ri,xi,yi)(r_i, x_i, y_i) satisfies ri=axi+byir_i = a x_i + b y_i, and the new row is the old one minus qq times the current one.

python · try it yourself
def ext_gcd(a, b):
    """Return (g, x, y) with a*x + b*y == g == gcd(a, b)."""
    r0, x0, y0 = a, 1, 0
    r1, x1, y1 = b, 0, 1
    while 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

for a, b in [(240, 46), (1071, 462), (17, 3120)]:
    g, x, y = ext_gcd(a, b)
    print(f"gcd({a}, {b}) = {g} = {a}*({x}) + {b}*({y})", a * x + b * y == g)
gcd(240, 46) = 2 = 240*(-9) + 46*(47) True
gcd(1071, 462) = 21 = 1071*(-3) + 462*(7) True
gcd(17, 3120) = 1 = 17*(-367) + 3120*(2) True

From Bézout to inverses

If gcd⁡(a,n)=1\gcd(a, n) = 1, then ax+ny=1ax + ny = 1, and reducing modulo nn gives ax≡1(modn)ax \equiv 1 \pmod{n}: xx is the inverse of aa modulo nn. This is exactly how RSA computes its private exponent d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n), and it is what pow(e, -1, phi) does internally.

python · try it yourself
def ext_gcd(a, b):
    r0, x0, r1, x1 = a, 1, b, 0
    while r1:
        q = r0 // r1
        r0, r1, x0, x1 = r1, r0 - q * r1, x1, x0 - q * x1
    return r0, x0

def inverse(a, n):
    g, x = ext_gcd(a % n, n)
    if g != 1:
        raise ValueError(f"{a} has no inverse mod {n} (gcd {g})")
    return x % n

e, phi = 17, 3120
d = inverse(e, phi)
print(d, (e * d) % phi, pow(e, -1, phi))
2753 1 2753

Size of the coefficients

The coefficients never get large: Bézout coefficients from the algorithm satisfy ∣x∣≤b/(2g)\lvert x \rvert \le b / (2g) and ∣y∣≤a/(2g)\lvert y \rvert \le a / (2g) (when a,b>0a, b > 0, apart from trivial cases). So inverses modulo a 2048-bit number are themselves at most 2048 bits, and computing them is fast.

In software

  • Every big-number library has an invert/modInverse function built on the extended Euclidean algorithm (or its binary variant); OpenSSL's is BN_mod_inverse.
  • Elliptic-curve point addition needs one modular inverse per operation, so libraries use projective coordinates to postpone the division until the very end.

Exercises

Exercise 1: By hand

Find integers x,yx, y with 35x+12y=135x + 12y = 1.

Answer

x=−1x = -1, y=3y = 3 (one solution).

Solution

35=2⋅12+1135 = 2 \cdot 12 + 11, 12=1⋅11+112 = 1 \cdot 11 + 1. Back-substitute: 1=12−11=12−(35−2⋅12)=3⋅12−351 = 12 - 11 = 12 - (35 - 2 \cdot 12) = 3 \cdot 12 - 35. So x=−1x = -1, y=3y = 3: −35+36=1-35 + 36 = 1.

Exercise 2: An inverse

Use Exercise 1 to find the inverse of 12 modulo 35.

Answer
Solution

From 35⋅(−1)+12⋅3=135 \cdot (-1) + 12 \cdot 3 = 1, reducing modulo 35 gives 12⋅3≡1(mod35)12 \cdot 3 \equiv 1 \pmod{35}. Check: 36=35+136 = 35 + 1.

Exercise 3: No inverse (code)

Use ext_gcd to explain why 21 has no inverse modulo 91, and find the smallest positive integer of the form 21x+91y21x + 91y.

Answer

gcd⁡(21,91)=7\gcd(21, 91) = 7, so the smallest positive value is 7, never 1.

Solution
python · try it yourself
def ext_gcd(a, b):
    r0, x0, y0, r1, x1, y1 = a, 1, 0, b, 0, 1
    while r1:
        q = r0 // r1
        r0, r1, x0, x1, y0, y1 = r1, r0 - q * r1, x1, x0 - q * x1, y1, y0 - q * y1
    return r0, x0, y0
print(ext_gcd(21, 91))
(7, -4, 1)

Every value 21x+91y21x + 91y is a multiple of 7, so 21x≡1(mod91)21x \equiv 1 \pmod{91} is impossible.

Test yourself

Bézout's identity says that gcd⁡(a,b)\gcd(a, b) is…

  1. the largest number of the form ax+byax + by
  2. the smallest positive number of the form ax+byax + by
  3. always 1
  4. abab divided by the lcm squared

If ax+ny=1ax + ny = 1, then the inverse of aa modulo nn is…

  1. yy
  2. x mod nx \bmod n
  3. a mod na \bmod n
  4. n−an - a

RSA uses the extended Euclidean algorithm to compute…

  1. the primes pp and qq
  2. the private exponent d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n)
  3. the ciphertext
  4. a hash