GCD, modular arithmetic & the Euclidean algorithm
◈ 7 cardsEuclid's algorithm and its O(lg b) Fibonacci worst case, extended Euclid for modular inverses, and fast modular exponentiation by repeated squaring.
The setting: arithmetic on integers measured in bits
Number-theoretic algorithms operate on integers, but we measure their cost by the number of bits in the input, not by the value. If is a -bit number then , and an algorithm is polynomial-time only if it runs in time polynomial in . This is why testing every divisor up to is not polynomial — there are about of them — while the Euclidean algorithm, which runs in arithmetic operations, is.
Divisibility, gcd, and the recursion theorem
We write (" divides ") when $a = kd$ for some integer . The greatest common divisor is the largest integer dividing both and . Two integers are relatively prime when .
The whole algorithm rests on one fact, the GCD recursion theorem:
Why it holds: any common divisor of and also divides (a linear combination of and ), and conversely. So the two pairs share exactly the same set of common divisors, hence the same greatest one.
Euclid's algorithm
Apply the recursion until the second argument is , then return the first (since ):
Worked example — . Each line applies :
- : , so
- : , so
- : , so
- . ✓
Running time (Lamé's theorem). The worst case for a given number of steps is consecutive Fibonacci numbers: makes the most recursive calls of any pair with . Because grows exponentially, the number of calls is . So Euclid is arithmetic operations — logarithmic in the value, linear in the bit length.
Extended Euclid and modular inverses
returns a triple where — the Bézout coefficients. The recursion carries the coefficients back up: if the recursive call on returns , then
so we return . This is the engine for modular inverses: exists iff , and then it is from . (Take the positive representative: may come back negative.) Modular inverses are exactly what RSA key generation needs in lesson 8.2.
Modular exponentiation by repeated squaring
RSA encrypts with for huge , so we can never multiply times. Instead use the binary expansion of the exponent: scanning the bits of , square the running value for every bit and multiply in for every -bit. That is modular multiplications:
Reducing after every step keeps every intermediate value below , so the numbers never blow up. With multiplications, each bit operations, the total is bit operations — the cost of one RSA decryption.