TExcelTAD
Home › Discrete Mathematics › The GCD and Euclid's Algorithm

The GCD and Euclid's Algorithm

The greatest common divisor gcd⁡(a,b)\gcd(a, b) is the largest integer dividing both aa and bb (not both zero). Euclid's algorithm computes it with a handful of remainders, even for numbers with hundreds of digits, and its extended version finds the coefficients that power modular inverses and RSA.

Euclid's algorithm

The key lemma: for b>0b > 0,

gcd⁡(a,b)=gcd⁡(b,rem⁡(a,b))\gcd(a, b) = \gcd(b, \operatorname{rem}(a, b))

Proof. Write a=qb+ra = qb + r. Any common divisor of aa and bb divides r=a−qbr = a - qb, and any common divisor of bb and rr divides a=qb+ra = qb + r. So the pairs (a,b)(a, b) and (b,r)(b, r) have exactly the same common divisors, hence the same greatest one. ■\blacksquare

Repeat until the remainder is 0; then gcd⁡(g,0)=g\gcd(g, 0) = g. The second number strictly decreases, so the algorithm terminates. In fact it at least halves every two steps, so the number of steps is O(log⁡b)O(\log b).

python · try it yourself
def euclid(a, b, trace=False):
    while b:
        if trace:
            print(f"gcd({a}, {b}): {a} = {a // b}*{b} + {a % b}")
        a, b = b, a % b
    return a

print("result:", euclid(1071, 462, trace=True))
gcd(1071, 462): 1071 = 2*462 + 147
gcd(462, 147): 462 = 3*147 + 21
gcd(147, 21): 147 = 7*21 + 0
result: 21

Bézout's identity

Theorem. gcd⁡(a,b)\gcd(a, b) is the smallest positive integer linear combination sa+tbsa + tb (s,t∈Zs, t \in \mathbb{Z}). In particular there are integers s,ts, t with

gcd⁡(a,b)=sa+tb\gcd(a, b) = s a + t b

Proof sketch. Let mm be the smallest positive linear combination (it exists by well ordering). Every common divisor of a,ba, b divides mm, so gcd⁡(a,b)≤m\gcd(a, b) \le m. Conversely, rem⁡(a,m)=a−qm\operatorname{rem}(a, m) = a - qm is also a linear combination and is smaller than mm, so it must be 0: m∣am \mid a, and likewise m∣bm \mid b. So mm is a common divisor and m≤gcd⁡(a,b)m \le \gcd(a, b). ■\blacksquare

Corollaries: every common divisor divides the gcd, and the linear combinations of aa and bb are exactly the multiples of gcd⁡(a,b)\gcd(a, b). That solves the water-jug puzzle: with jugs of size aa and bb you can measure exactly the multiples of gcd⁡(a,b)\gcd(a, b) up to max⁡(a,b)\max(a, b).

The extended Euclidean algorithm

The coefficients s,ts, t can be tracked through Euclid's steps. Keep two rows (r,s,t)(r, s, t) with r=sa+tbr = sa + tb, and subtract multiples of one row from the other:

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

for a, b in [(1071, 462), (240, 46), (26, 7)]:
    g, s, t = ext_gcd(a, b)
    print(f"gcd({a}, {b}) = {g} = ({s})*{a} + ({t})*{b}  check: {s * a + t * b}")
gcd(1071, 462) = 21 = (-3)*1071 + (7)*462  check: 21
gcd(240, 46) = 2 = (-9)*240 + (47)*46  check: 2
gcd(26, 7) = 1 = (3)*26 + (-11)*7  check: 1

The last line says 1=3⋅26+(−11)⋅71 = 3 \cdot 26 + (-11) \cdot 7. Read modulo 26, the first term vanishes: (−11)⋅7≡1(mod26)(-11) \cdot 7 \equiv 1 \pmod{26}, so −11≡15-11 \equiv 15 is the inverse of 7 modulo 26. Inverses are the topic of Inverses, Fermat and Euler.

Coprime numbers

aa and bb are relatively prime (coprime) when gcd⁡(a,b)=1\gcd(a, b) = 1. Then 1=sa+tb1 = sa + tb, which gives a useful lemma:

Lemma. If a∣bca \mid bc and gcd⁡(a,b)=1\gcd(a, b) = 1, then a∣ca \mid c.

Proof. c=c(sa+tb)=csa+t(bc)c = c(sa + tb) = csa + t(bc). Both terms are multiples of aa. ■\blacksquare

The least common multiple follows from the gcd: lcm⁡(a,b)=abgcd⁡(a,b)\operatorname{lcm}(a, b) = \frac{ab}{\gcd(a, b)} for positive a,ba, b.

In software

Python's math.gcd and math.lcm use these algorithms; pow(a, -1, n) (Python 3.8+) computes a modular inverse with the extended algorithm. Fractions libraries reduce with the gcd after every operation. Games use lcm to find when repeating cycles line up (two animations of 6 and 8 frames realign every 24 frames).

Exercises

Exercise 1: Euclid by hand

Compute gcd⁡(252,198)\gcd(252, 198) with Euclid's algorithm.

Answer
Solution
252=1⋅198+54198=3⋅54+3654=1⋅36+1836=2⋅18+0\begin{aligned} 252 &= 1 \cdot 198 + 54 \\ 198 &= 3 \cdot 54 + 36 \\ 54 &= 1 \cdot 36 + 18 \\ 36 &= 2 \cdot 18 + 0 \end{aligned}

The last non-zero remainder is 18.

Exercise 2: Bézout coefficients

Find integers s,ts, t with s⋅35+t⋅22=1s \cdot 35 + t \cdot 22 = 1.

Answer

s=−5s = -5, t=8t = 8 (one solution).

Solution

35=1⋅22+1335 = 1 \cdot 22 + 13, 22=1⋅13+922 = 1 \cdot 13 + 9, 13=1⋅9+413 = 1 \cdot 9 + 4, 9=2⋅4+19 = 2 \cdot 4 + 1. Back-substitute:

1=9−2⋅4=9−2(13−9)=3⋅9−2⋅13=3(22−13)−2⋅13=3⋅22−5⋅13=3⋅22−5(35−22)=8⋅22−5⋅35\begin{aligned} 1 &= 9 - 2 \cdot 4 = 9 - 2(13 - 9) = 3 \cdot 9 - 2 \cdot 13 \\ &= 3(22 - 13) - 2 \cdot 13 = 3 \cdot 22 - 5 \cdot 13 \\ &= 3 \cdot 22 - 5(35 - 22) = 8 \cdot 22 - 5 \cdot 35 \end{aligned}

Other solutions are s=−5+22ks = -5 + 22k, t=8−35kt = 8 - 35k.

Exercise 3: Jugs (code)

With jugs of 21 and 26 gallons, which amounts from 1 to 26 can be measured? With 12 and 18?

Answer

All of 1 to 26 with 21 and 26 (gcd 1); only 6, 12, 18 with 12 and 18 (gcd 6).

Solution

Search the jug states (fill, empty, pour) with breadth-first search and collect every amount that appears:

python · try it yourself
from collections import deque
from math import gcd

def measurable(A, B):
    seen, q = {(0, 0)}, deque([(0, 0)])
    while q:
        a, b = q.popleft()
        pa, pb = min(a, B - b), min(b, A - a)
        for s in [(A, b), (a, B), (0, b), (a, 0), (a - pa, b + pa), (a + pb, b - pb)]:
            if s not in seen:
                seen.add(s)
                q.append(s)
    return sorted({x for s in seen for x in s if x > 0})

print(measurable(21, 26) == list(range(1, 27)), gcd(21, 26))
print(measurable(12, 18), gcd(12, 18))
True 1
[6, 12, 18] 6

Test yourself

What is gcd⁡(48,18)\gcd(48, 18)?

  1. 2
  2. 3
  3. 6
  4. 9

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

  1. a⋅ba \cdot b
  2. the smallest positive integer linear combination of aa and bb
  3. always 1
  4. the largest linear combination

If gcd⁡(12,35)=1\gcd(12, 35) = 1 and 12∣35c12 \mid 35c, what follows?

  1. 35∣c35 \mid c
  2. 12∣c12 \mid c
  3. c=0c = 0
  4. nothing