The GCD and Euclid's Algorithm
The greatest common divisor is the largest integer dividing both and (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 ,
Proof. Write . Any common divisor of and divides , and any common divisor of and divides . So the pairs and have exactly the same common divisors, hence the same greatest one.
Repeat until the remainder is 0; then . The second number strictly decreases, so the algorithm terminates. In fact it at least halves every two steps, so the number of steps is .
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. is the smallest positive integer linear combination (). In particular there are integers with
Proof sketch. Let be the smallest positive linear combination (it exists by well ordering). Every common divisor of divides , so . Conversely, is also a linear combination and is smaller than , so it must be 0: , and likewise . So is a common divisor and .
Corollaries: every common divisor divides the gcd, and the linear combinations of and are exactly the multiples of . That solves the water-jug puzzle: with jugs of size and you can measure exactly the multiples of up to .
The extended Euclidean algorithm
The coefficients can be tracked through Euclid's steps. Keep two rows with , and subtract multiples of one row from the other:
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 . Read modulo 26, the first term vanishes: , so is the inverse of 7 modulo 26. Inverses are the topic of Inverses, Fermat and Euler.
Coprime numbers
and are relatively prime (coprime) when . Then , which gives a useful lemma:
Lemma. If and , then .
Proof. . Both terms are multiples of .
The least common multiple follows from the gcd: for positive .
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 with Euclid's algorithm.
Answer
Solution
The last non-zero remainder is 18.
Exercise 2: Bézout coefficients
Find integers with .
Answer
, (one solution).
Solution
, , , . Back-substitute:
Other solutions are , .
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:
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 ?
- 2
- 3
- 6
- 9
Bézout's identity says is…
- the smallest positive integer linear combination of and
- always 1
- the largest linear combination
If and , what follows?
- nothing