Euclidean Algorithm
The Euclidean algorithm finds the greatest common divisor (GCD) of two whole numbers: the largest number that divides both without a remainder. It was described by Euclid around 300 BC, which makes it one of the oldest algorithms still in everyday use. It powers fraction simplification, cryptography (RSA keys), and calendar and gear calculations.
For example, gcd(48, 18) = 6: 6 divides both 48 and 18, and no larger number does.
The brute-force way
The obvious approach tries every candidate from the smaller number downwards:
def gcd_brute(a, b):
tries = 0
for d in range(min(a, b), 0, -1):
tries += 1
if a % d == 0 and b % d == 0:
return d, tries
print(gcd_brute(48, 18))
print(gcd_brute(1071, 462))
print(gcd_brute(1_000_003, 999_983)) # two primes: the GCD is 1(6, 13)
(21, 442)
(1, 999983)
For two large numbers with GCD 1, this tries almost a million candidates.
Euclid's insight
Any number that divides both a and b also divides their difference a - b. So gcd(a, b) = gcd(a - b, b). Subtracting repeatedly is the same as taking the remainder, which gives the modern form:
gcd(a, b) = gcd(b, a mod b) and gcd(a, 0) = aEach step replaces the pair by a smaller pair with the same GCD, until the second number becomes 0.
def gcd(a, b):
while b != 0:
print(f"gcd({a}, {b}): {a} = {a // b} * {b} + {a % b}")
a, b = b, a % b
return a
print("result:", gcd(1071, 462))gcd(1071, 462): 1071 = 2 * 462 + 147
gcd(462, 147): 462 = 3 * 147 + 21
gcd(147, 21): 147 = 7 * 21 + 0
result: 21
Three division steps instead of 442 tries. The remainders shrink very quickly: it can be shown that every two steps at least halve the smaller number, so the number of steps is O(log(min(a, b))).
The subtraction version
Euclid's original formulation used subtraction instead of division. It is easier to do by hand but can be much slower when one number is far bigger than the other:
def gcd_subtract(a, b):
steps = 0
while a != b:
if a > b:
a -= b
else:
b -= a
steps += 1
return a, steps
def gcd_mod(a, b):
steps = 0
while b:
a, b = b, a % b
steps += 1
return a, steps
for a, b in [(48, 18), (1071, 462), (1_000_000, 3)]:
print(f"{a}, {b}: subtraction {gcd_subtract(a, b)}, remainder {gcd_mod(a, b)}")48, 18: subtraction (6, 4), remainder (6, 3)
1071, 462: subtraction (21, 11), remainder (21, 3)
1000000, 3: subtraction (1, 333335), remainder (1, 2)
Recursive form
The rule gcd(a, b) = gcd(b, a mod b) is naturally recursive:
import math
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
print(gcd(270, 192), math.gcd(270, 192)) # Python has it built in
print(gcd(17, 5), gcd(0, 9), gcd(9, 0))6 6
1 9 9
Applications
Simplifying fractions: divide numerator and denominator by their GCD. Least common multiple: lcm(a, b) = a · b / gcd(a, b), useful for "when do two cycles line up again?".
from math import gcd
def simplify(num, den):
g = gcd(num, den)
return num // g, den // g
def lcm(a, b):
return a * b // gcd(a, b)
print(simplify(84, 126))
print("buses every 12 and 18 minutes meet every", lcm(12, 18), "minutes")(2, 3)
buses every 12 and 18 minutes meet every 36 minutes
The extended Euclidean algorithm also finds integers x and y with a·x + b·y = gcd(a, b). That is how RSA computes a modular inverse (the private key):
def extended_gcd(a, b):
if b == 0:
return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
g, x, y = extended_gcd(240, 46)
print(f"gcd = {g}, {x}*240 + {y}*46 = {x * 240 + y * 46}")
# modular inverse of 7 modulo 40: the number k with 7*k % 40 == 1
g, x, _ = extended_gcd(7, 40)
print("inverse of 7 mod 40:", x % 40, "check:", 7 * (x % 40) % 40)gcd = 2, -9*240 + 47*46 = 2
inverse of 7 mod 40: 23 check: 1
Test yourself
What is gcd(84, 36)?
- 4
- 6
- 12
- 18
What rule does each step of the Euclidean algorithm use?
- gcd(a, b) = gcd(a + b, b)
- gcd(a, b) = gcd(b, a mod b)
- gcd(a, b) = a · b
- gcd(a, b) = gcd(a / 2, b / 2)
Why is the remainder version much faster than trying every candidate?
- It uses floating point
- The numbers shrink at least by half every two steps, so it takes O(log n) steps
- It only works for primes
- It caches results