GCD and Euclid's Algorithm
The greatest common divisor of two numbers is needed to simplify fractions, to decide whether a modular inverse exists and to generate RSA keys. Euclid's algorithm, more than 2300 years old, computes it in a number of steps proportional to the number of digits, not to the size of the numbers.
Definition
The greatest common divisor of integers , not both 0, is the largest integer dividing both. If , then and are coprime (relatively prime). By convention .
The least common multiple is for nonzero .
The key lemma
If , then .
Proof. A common divisor of and divides ; a common divisor of and divides . So both pairs have the same set of common divisors, and in particular the same largest one.
Replacing by makes the numbers shrink until the remainder is 0:
from math import gcd
def euclid(a, b, verbose=False):
while b:
if verbose:
print(f"{a} = {a // b}*{b} + {a % b}")
a, b = b, a % b
return abs(a)
print("gcd =", euclid(1071, 462, verbose=True))
print(gcd(1071, 462), gcd(2**64, 6**30), gcd(17, 0))1071 = 2*462 + 147
462 = 3*147 + 21
147 = 7*21 + 0
gcd = 21
21 1073741824 17
How fast is it?
Every two steps the first number at least halves: if then , and if then . So the number of steps is at most about . Lamé's theorem sharpens this: the worst inputs are consecutive Fibonacci numbers, where every quotient is 1.
def steps(a, b):
count = 0
while b:
a, b = b, a % b
count += 1
return count
fib = [1, 1]
while len(fib) < 60:
fib.append(fib[-1] + fib[-2])
print("F59, F58:", fib[59], fib[58], " steps:", steps(fib[59], fib[58]))
a = 2**2048 - 159
print("2048-bit example steps:", steps(a, 3**1000))F59, F58: 1548008755920 956722026041 steps: 58
2048-bit example steps: 903
Even for 2048-bit numbers the loop runs only about a thousand times, which is why RSA key generation can afford many gcd checks.
Binary GCD
Hardware is fast at shifts and subtraction. Stein's binary GCD uses , for odd , and . It avoids division entirely, and libraries such as GMP use variants of it.
def binary_gcd(a, b):
if a == 0 or b == 0:
return a | b
shift = ((a | b) & -(a | b)).bit_length() - 1 # common factors of 2
a >>= (a & -a).bit_length() - 1
while b:
b >>= (b & -b).bit_length() - 1
if a > b:
a, b = b, a
b -= a
return a << shift
print(binary_gcd(1071, 462), binary_gcd(48, 180), binary_gcd(2**40, 2**12 * 3))21 12 4096
In software
math.gcd,math.lcm, Java'sBigInteger.gcd, Rust'snum::integer::gcdall use Euclid or binary GCD.- RSA key generation checks ; a famous 2012 study found thousands of real RSA keys sharing a prime factor, broken instantly by computing pairwise gcds of public moduli (Factoring Algorithms).
- Fractions (
fractions.Fraction) are kept in lowest terms by dividing by the gcd after every operation.
Exercises
Exercise 1: By hand
Compute with Euclid's algorithm and then .
Answer
, .
Solution
, , , . So the gcd is 18, and .
Exercise 2: Consecutive numbers
Prove that for every integer .
Answer
Any common divisor divides .
Solution
By the key lemma, . In words: consecutive integers never share a factor. Euclid used this to show there are infinitely many primes (Prime Numbers).
Exercise 3: Shared factors in keys (code)
Three toy RSA moduli are , , . Compute all pairwise gcds. Which moduli share a prime, and what are their factors?
Answer
All three share the prime 31: , , .
Solution
from math import gcd
from itertools import combinations
ns = {"n1": 899, "n2": 1147, "n3": 1271}
for (x, a), (y, b) in combinations(ns.items(), 2):
g = gcd(a, b)
print(x, y, "gcd:", g, " factors:", (g, a // g), (g, b // g))n1 n2 gcd: 31 factors: (31, 29) (31, 37)
n1 n3 gcd: 31 factors: (31, 29) (31, 41)
n2 n3 gcd: 31 factors: (31, 37) (31, 41)
All three share the prime 31, so one gcd per pair factors every modulus. A single bad random number generator that repeats a prime breaks all the keys that use it.
Test yourself
Euclid's algorithm replaces by…
Which inputs make Euclid's algorithm take the most steps for their size?
- powers of two
- consecutive Fibonacci numbers
- equal numbers
- primes
The number of steps of Euclid's algorithm on -bit inputs grows like…
- a constant times