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 , not both zero, when , and . That gives
EUCLID(a, b) // a >= b >= 0
1 while b != 0
2 (a, b) = (b, a mod b) // one division step
3 return aEach 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: can be as large as .
Remainders halve every two steps
A first bound: if , then . Indeed, if the remainder is less than ; and if the quotient is 1 and the remainder is . After two steps the first number of the pair has gone from to , so it at least halves every two steps, and the number of steps is at most : linear in the number of bits. The Fibonacci numbers make this bound exact.
Lamé's theorem
Write , , .
Theorem (Lamé, 1844). If and EUCLID(a, b) performs division steps, then and .
Proof
Induction on . For : and gives .
For : the first step leads to the pair , on which the algorithm performs further steps, and (the remainder is nonzero, since more steps follow). By induction and . Since , the quotient is at least 1, so
The bound is tight: consecutive Fibonacci numbers take the most steps, because every quotient is 1 and every step goes from to . The program finds, for each , the smallest pair that needs steps.
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 with , a pair with needs fewer than steps. In other words, the number of division steps is at most . For a 1024-bit that is at most about 1476 steps, and random inputs need fewer:
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 steps, matching a classical result of Heilbronn and Dixon: on average about steps.
Bit complexity
Each step is one division of -bit numbers, which the schoolbook method does in bit operations, and there are steps, so is an easy bound. A sharper accounting shows in total: dividing by costs about bit operations for the quotient , and the quotients' logarithms add up to because their product is at most . 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 with (The Extended Euclidean Algorithm). From and : if , then .
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 , the coefficient is the inverse of modulo , needed for RSA keys in RSA: Key Generation and Cost.
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.)
#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?
- Powers of 2
- Consecutive Fibonacci numbers
- Two primes
- Equal numbers
By Lamé's theorem, if and Euclid's algorithm makes 10 division steps, then
How does the number of division steps of Euclid's algorithm grow with the number of bits of the inputs?
What does extended Euclid return for that RSA needs?
- A prime factor of
- The inverse of modulo , as the coefficient in
- The order of