TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Euclid's Algorithm and Its Running Time

Euclid's Algorithm and Its Running Time

Cryptography computes with numbers of hundreds or thousands of bits, so "polynomial time" there means polynomial in the number of bits, not in the numbers themselves. Euclid's algorithm for the greatest common divisor is the first test case: it is more than two thousand years old, and its worst case is governed by the Fibonacci numbers. This section of the course takes the running-time view of four number-theoretic algorithms; the mathematics behind them (divisibility, congruences, why RSA works) is developed in full in Number Theory & Cryptography, starting with The Euclidean Algorithm.

The algorithm

For integers a≥b≥0a \ge b \ge 0, not both zero, gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) when b>0b > 0, and gcd⁡(a,0)=a\gcd(a, 0) = a. That gives

text
EUCLID(a, b)                 // a >= b >= 0
1  while b != 0
2      (a, b) = (b, a mod b) // one division step
3  return a

Each step replaces the pair by a smaller one, so the loop ends. How many steps can it take? The remainders shrink, but in principle slowly: a mod ba \bmod b can be as large as b−1b - 1.

Remainders halve every two steps

A first bound: if b≤ab \le a, then a mod b<a/2a \bmod b < a/2. Indeed, if b≤a/2b \le a/2 the remainder is less than b≤a/2b \le a/2; and if b>a/2b > a/2 the quotient is 1 and the remainder is a−b<a/2a - b < a/2. After two steps the first number of the pair has gone from aa to a mod ba \bmod b, so it at least halves every two steps, and the number of steps is at most 2lg⁡a+O(1)2 \lg a + O(1): linear in the number of bits. The Fibonacci numbers make this bound exact.

Lamé's theorem

Write F0=0F_0 = 0, F1=1F_1 = 1, Fk=Fk−1+Fk−2F_{k} = F_{k-1} + F_{k-2}.

Theorem (Lamé, 1844). If a>b≥1a > b \ge 1 and EUCLID(a, b) performs k≥1k \ge 1 division steps, then a≥Fk+2a \ge F_{k+2} and b≥Fk+1b \ge F_{k+1}.

Proof

Induction on kk. For k=1k = 1: b≥1=F2b \ge 1 = F_2 and a>ba > b gives a≥2=F3a \ge 2 = F_3.

For k≥2k \ge 2: the first step leads to the pair (b,a mod b)(b, a \bmod b), on which the algorithm performs k−1≥1k - 1 \ge 1 further steps, and b>a mod b≥1b > a \bmod b \ge 1 (the remainder is nonzero, since more steps follow). By induction b≥Fk+1b \ge F_{k+1} and a mod b≥Fka \bmod b \ge F_k. Since a>ba > b, the quotient ⌊a/b⌋\lfloor a/b \rfloor is at least 1, so

a=⌊a/b⌋ b+(a mod b)≥b+(a mod b)≥Fk+1+Fk=Fk+2.a = \lfloor a/b \rfloor\, b + (a \bmod b) \ge b + (a \bmod b) \ge F_{k+1} + F_k = F_{k+2}.

The bound is tight: consecutive Fibonacci numbers take the most steps, because every quotient is 1 and every step goes from (Fj+1,Fj)(F_{j+1}, F_j) to (Fj,Fj−1)(F_j, F_{j-1}). The program finds, for each kk, the smallest pair that needs kk steps.

python · try it yourself
def steps(a, b):
    count = 0
    while b:
        a, b = b, a % b
        count += 1
    return count

smallest = {}
for a in range(2, 400):
    for b in range(1, a):
        k = steps(a, b)
        smallest.setdefault(k, (a, b))
fib = [0, 1]
while len(fib) < 16:
    fib.append(fib[-1] + fib[-2])
for k, pair in sorted(smallest.items()):
    print(f"{k:2} steps: first pair {pair},  (F_{k + 2}, F_{k + 1}) = ({fib[k + 2]}, {fib[k + 1]})")
 1 steps: first pair (2, 1),  (F_3, F_2) = (2, 1)
 2 steps: first pair (3, 2),  (F_4, F_3) = (3, 2)
 3 steps: first pair (5, 3),  (F_5, F_4) = (5, 3)
 4 steps: first pair (8, 5),  (F_6, F_5) = (8, 5)
 5 steps: first pair (13, 8),  (F_7, F_6) = (13, 8)
 6 steps: first pair (21, 13),  (F_8, F_7) = (21, 13)
 7 steps: first pair (34, 21),  (F_9, F_8) = (34, 21)
 8 steps: first pair (55, 34),  (F_10, F_9) = (55, 34)
 9 steps: first pair (89, 55),  (F_11, F_10) = (89, 55)
10 steps: first pair (144, 89),  (F_12, F_11) = (144, 89)
11 steps: first pair (233, 144),  (F_13, F_12) = (233, 144)
12 steps: first pair (377, 233),  (F_14, F_13) = (377, 233)

Since Fk+1≥ϕk−1F_{k+1} \ge \phi^{k-1} with ϕ=(1+5)/2≈1.618\phi = (1 + \sqrt{5})/2 \approx 1.618, a pair with b<ϕk−1b < \phi^{k-1} needs fewer than kk steps. In other words, the number of division steps is at most 1+log⁡ϕb≈1.44lg⁡b+11 + \log_\phi b \approx 1.44 \lg b + 1. For a 1024-bit bb that is at most about 1476 steps, and random inputs need fewer:

python · try it yourself
import random
from math import log

def steps(a, b):
    count = 0
    while b:
        a, b = b, a % b
        count += 1
    return count

phi = (1 + 5 ** 0.5) / 2
rng = random.Random(2024)
for bits in [32, 256, 1024]:
    pairs = [(rng.getrandbits(bits) | 1 << (bits - 1), rng.getrandbits(bits)) for _ in range(200)]
    pairs = [(max(p), min(p)) for p in pairs]
    worst = max(steps(a, b) for a, b in pairs)
    avg = sum(steps(a, b) for a, b in pairs) / len(pairs)
    bound = 1 + bits * log(2) / log(phi)
    print(f"{bits:5}-bit numbers: average {avg:7.1f} steps, worst of 200 {worst:5}, Lame bound {bound:7.1f}")
   32-bit numbers: average    18.4 steps, worst of 200    28, Lame bound    47.1
  256-bit numbers: average   149.9 steps, worst of 200   176, Lame bound   369.7
 1024-bit numbers: average   599.3 steps, worst of 200   650, Lame bound  1476.0

The average is about 0.58lg⁡b0.58 \lg b steps, matching a classical result of Heilbronn and Dixon: on average about 12ln⁡2π2ln⁡b≈0.843ln⁡b≈0.584lg⁡b\frac{12 \ln 2}{\pi^2} \ln b \approx 0.843 \ln b \approx 0.584 \lg b steps.

Bit complexity

Each step is one division of β\beta-bit numbers, which the schoolbook method does in O(β2)O(\beta^2) bit operations, and there are O(β)O(\beta) steps, so O(β3)O(\beta^3) is an easy bound. A sharper accounting shows O(β2)O(\beta^2) in total: dividing aa by bb costs about lg⁡b⋅(1+lg⁡q)\lg b \cdot (1 + \lg q) bit operations for the quotient qq, and the quotients' logarithms add up to O(β)O(\beta) because their product is at most aa. Either way, Euclid's algorithm is polynomial in the input length, unlike trial division, which is exponential in it.

Extended Euclid

The extended algorithm also returns integers x,yx, y with ax+by=gcd⁡(a,b)ax + by = \gcd(a, b) (The Extended Euclidean Algorithm). From gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b) and a mod b=a−⌊a/b⌋ba \bmod b = a - \lfloor a/b \rfloor b: if bx′+(a mod b)y′=db x' + (a \bmod b) y' = d, then ay′+b(x′−⌊a/b⌋y′)=da y' + b(x' - \lfloor a/b \rfloor y') = d.

text
EXTENDED-EUCLID(a, b)
1  if b == 0
2      return (a, 1, 0)
3  (d, x', y') = EXTENDED-EUCLID(b, a mod b)
4  return (d, y', x' - floor(a / b) * y')

It makes exactly as many calls as Euclid's algorithm makes steps, plus one, so Lamé's bound applies unchanged. Its main use here: when gcd⁡(a,n)=1\gcd(a, n) = 1, the coefficient xx is the inverse of aa modulo nn, needed for RSA keys in RSA: Key Generation and Cost.

python · try it yourself
def extended_euclid(a, b, depth=0):
    if b == 0:
        print(f"{'  ' * depth}({a}, 0) -> d = {a}, x = 1, y = 0")
        return a, 1, 0
    d, x1, y1 = extended_euclid(b, a % b, depth + 1)
    x, y = y1, x1 - (a // b) * y1
    print(f"{'  ' * depth}({a}, {b}) -> d = {d}, x = {x}, y = {y}")
    return d, x, y

d, x, y = extended_euclid(240, 46)
print(f"240 * {x} + 46 * {y} = {240 * x + 46 * y}")
d, x, y = extended_euclid(17, 3120)
print("inverse of 17 mod 3120:", x % 3120, " check:", 17 * (x % 3120) % 3120)
          (2, 0) -> d = 2, x = 1, y = 0
        (4, 2) -> d = 2, x = 0, y = 1
      (6, 4) -> d = 2, x = 1, y = -1
    (10, 6) -> d = 2, x = -1, y = 2
  (46, 10) -> d = 2, x = 2, y = -9
(240, 46) -> d = 2, x = -9, y = 47
240 * -9 + 46 * 47 = 2
          (1, 0) -> d = 1, x = 1, y = 0
        (8, 1) -> d = 1, x = 0, y = 1
      (9, 8) -> d = 1, x = 1, y = -1
    (17, 9) -> d = 1, x = -1, y = 2
  (3120, 17) -> d = 1, x = 2, y = -367
(17, 3120) -> d = 1, x = -367, y = 2
inverse of 17 mod 3120: 2753  check: 1

In C++

Extended Euclid in C++, iteratively, on consecutive Fibonacci numbers, counting the steps. (Bézout coefficients of consecutive Fibonacci numbers are again Fibonacci numbers, up to sign.)

cpp · try it yourself
#include <cstdio>
#include <initializer_list>

struct Result { long long d, x, y; int steps; };

Result extended_euclid(long long a, long long b) {
    long long x0 = 1, y0 = 0, x1 = 0, y1 = 1;      // a = x0*A + y0*B, b = x1*A + y1*B
    int steps = 0;
    while (b != 0) {
        long long q = a / b, r = a % b;
        a = b; b = r;
        long long nx = x0 - q * x1, ny = y0 - q * y1;
        x0 = x1; y0 = y1; x1 = nx; y1 = ny;
        steps++;
    }
    return {a, x0, y0, steps};
}

int main() {
    long long f[60] = {0, 1};
    for (int i = 2; i < 60; i++) f[i] = f[i - 1] + f[i - 2];
    for (int k : {10, 25, 40}) {
        auto r = extended_euclid(f[k + 2], f[k + 1]);
        std::printf("gcd(F_%d, F_%d) = %lld in %d steps; %lld * %lld + %lld * %lld = %lld\n",
                    k + 2, k + 1, r.d, r.steps, f[k + 2], r.x, f[k + 1], r.y, f[k + 2] * r.x + f[k + 1] * r.y);
    }
}
gcd(F_12, F_11) = 1 in 10 steps; 144 * 34 + 89 * -55 = 1
gcd(F_27, F_26) = 1 in 25 steps; 196418 * -46368 + 121393 * 75025 = 1
gcd(F_42, F_41) = 1 in 40 steps; 267914296 * 63245986 + 165580141 * -102334155 = 1

Practise with Greatest Common Divisor.

Test yourself

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

  1. Powers of 2
  2. Consecutive Fibonacci numbers
  3. Two primes
  4. Equal numbers

By Lamé's theorem, if a>b≥1a > b \ge 1 and Euclid's algorithm makes 10 division steps, then

  1. b≥55b \ge 55
  2. b≥89b \ge 89
  3. a≥55a \ge 55
  4. b≥10b \ge 10

How does the number of division steps of Euclid's algorithm grow with the number of bits β\beta of the inputs?

  1. O(1)O(1)
  2. O(β)O(\beta)
  3. O(2β)O(2^\beta)
  4. O(2β)O(\sqrt{2^\beta})

What does extended Euclid return for gcd⁡(a,n)=1\gcd(a, n) = 1 that RSA needs?

  1. A prime factor of nn
  2. The inverse of aa modulo nn, as the coefficient xx in ax+ny=1ax + ny = 1
  3. an−1 mod na^{n-1} \bmod n
  4. The order of aa