TExcelTAD
Home › Number Theory & Cryptography › GCD and Euclid's Algorithm

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 gcd⁡(a,b)\gcd(a, b) of integers a,ba, b, not both 0, is the largest integer dividing both. If gcd⁡(a,b)=1\gcd(a, b) = 1, then aa and bb are coprime (relatively prime). By convention gcd⁡(a,0)=∣a∣\gcd(a, 0) = \lvert a \rvert.

The least common multiple is lcm⁡(a,b)=∣ab∣/gcd⁡(a,b)\operatorname{lcm}(a, b) = \lvert ab \rvert / \gcd(a, b) for nonzero a,ba, b.

The key lemma

If a=qb+ra = qb + r, then gcd⁡(a,b)=gcd⁡(b,r)\gcd(a, b) = \gcd(b, r).

Proof. A common divisor of aa and bb divides r=a−qbr = a - qb; a common divisor of bb and rr divides a=qb+ra = qb + r. So both pairs have the same set of common divisors, and in particular the same largest one.

Replacing (a,b)(a, b) by (b,a mod b)(b, a \bmod b) makes the numbers shrink until the remainder is 0:

gcd⁡(1071,462)=gcd⁡(462,147)1071=2⋅462+147=gcd⁡(147,21)462=3⋅147+21=gcd⁡(21,0)=21147=7⋅21\begin{aligned} \gcd(1071, 462) &= \gcd(462, 147) && 1071 = 2 \cdot 462 + 147 \\ &= \gcd(147, 21) && 462 = 3 \cdot 147 + 21 \\ &= \gcd(21, 0) = 21 && 147 = 7 \cdot 21 \end{aligned}
python · try it yourself
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 b≤a/2b \le a/2 then r<b≤a/2r < b \le a/2, and if b>a/2b > a/2 then r=a−b<a/2r = a - b < a/2. So the number of steps is at most about 2log⁡2a2\log_2 a. Lamé's theorem sharpens this: the worst inputs are consecutive Fibonacci numbers, where every quotient is 1.

python · try it yourself
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 gcd⁡(2a,2b)=2gcd⁡(a,b)\gcd(2a, 2b) = 2\gcd(a, b), gcd⁡(2a,b)=gcd⁡(a,b)\gcd(2a, b) = \gcd(a, b) for odd bb, and gcd⁡(a,b)=gcd⁡(a−b,b)\gcd(a, b) = \gcd(a - b, b). It avoids division entirely, and libraries such as GMP use variants of it.

python · try it yourself
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's BigInteger.gcd, Rust's num::integer::gcd all use Euclid or binary GCD.
  • RSA key generation checks gcd⁡(e,p−1)=1\gcd(e, p - 1) = 1; 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 gcd⁡(252,198)\gcd(252, 198) with Euclid's algorithm and then lcm⁡(252,198)\operatorname{lcm}(252, 198).

Answer

gcd⁡=18\gcd = 18, lcm⁡=2772\operatorname{lcm} = 2772.

Solution

252=1⋅198+54252 = 1 \cdot 198 + 54, 198=3⋅54+36198 = 3 \cdot 54 + 36, 54=1⋅36+1854 = 1 \cdot 36 + 18, 36=2⋅1836 = 2 \cdot 18. So the gcd is 18, and lcm⁡=252⋅198/18=14⋅198=2772\operatorname{lcm} = 252 \cdot 198 / 18 = 14 \cdot 198 = 2772.

Exercise 2: Consecutive numbers

Prove that gcd⁡(n,n+1)=1\gcd(n, n + 1) = 1 for every integer nn.

Answer

Any common divisor divides (n+1)−n=1(n + 1) - n = 1.

Solution

By the key lemma, gcd⁡(n+1,n)=gcd⁡(n,1)=1\gcd(n + 1, n) = \gcd(n, 1) = 1. 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 n1=899n_1 = 899, n2=1147n_2 = 1147, n3=1271n_3 = 1271. Compute all pairwise gcds. Which moduli share a prime, and what are their factors?

Answer

All three share the prime 31: 899=29⋅31899 = 29 \cdot 31, 1147=31⋅371147 = 31 \cdot 37, 1271=31⋅411271 = 31 \cdot 41.

Solution
python · try it yourself
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 (a,b)(a, b) by…

  1. (a−1,b)(a - 1, b)
  2. (b,a mod b)(b, a \bmod b)
  3. (a/b,b)(a / b, b)
  4. (ab,a+b)(ab, a + b)

Which inputs make Euclid's algorithm take the most steps for their size?

  1. powers of two
  2. consecutive Fibonacci numbers
  3. equal numbers
  4. primes

The number of steps of Euclid's algorithm on nn-bit inputs grows like…

  1. 2n2^n
  2. n2n^2
  3. a constant times nn
  4. 2n\sqrt{2^n}