Locking a message takes 17 multiplications. Factoring a 2048-bit key by trial division takes about 10308 divisions. Number theory lives in that gap.
Pick a message and watch the toy key lock and unlock it. Then drag the key size and watch the attacker's bar run away. Then we build, piece by piece, gcd, inverses, fast powers, RSA, prime tests and the Chinese remainder theorem.
You need division with a remainder and a little Python. We build the rest from zero.
Based on Chapter 31, Number-Theoretic Algorithms, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Polynomials and the FFT. Next: String Matching.
The round trip always uses the toy key n = 3233, e = 17, d = 2753 (Chapter 6). The bars are step counts on a log scale. Lock uses e = 65537: 16 squarings and 1 multiplication. Unlock uses a d as long as the key: about 1.5 multiplications per bit. Break is trial division up to the square root of n: about 2k/2 − 1 odd divisors. Better factoring methods exist; they are faster than trial division and still far too slow for large keys.
Chapter 0
Multiply two primes in one step, then try to split the product back apart
Take the primes 61 and 53. Their product, 3233, takes one multiplication. Now hand a stranger 3233 and ask for the two primes. The plain method is trial division: divide by 3, 5, 7 and so on until one divides evenly. It needs 26 odd tries to reach 53.
That gap is the whole chapter. Some operations on whole numbers are fast. Others look like their reverse and seem to be slow. Public-key cryptography builds a lock from that gap: anyone can close it, and only the holder of a secret can open it.
Pick a prime size and press New primes. The product appears at once. The yellow bar counts the odd divisors that trial division tries before it finds the smaller prime.
Illustrative. Trial division here tries 3, 5, 7 and every odd number after, up to the smaller prime. Each extra digit in the primes multiplies the work by about 10.
Worked number: with primes of d digits, the smaller prime is about 10d, so trial division needs about 10d / 2 tries. A real key uses primes of about 300 digits each, so the count is near 10300. Better methods exist, and they still struggle: the 232-digit number RSA-768 took a research team almost two years on hundreds of machines (Kleinjung et al., 2010).
The failure. Symptom: an attacker recovers a private key in seconds. Measure: count the bits of the public number n. Fix: make n large; toy keys like 3233 exist only to teach.
Chapter 1
Shrink a pair of numbers with one division at a time until the answer falls out
A floor is 252 cm by 105 cm. You want the largest square tile that covers it with no cutting. The tile side must divide 252 and 105. The largest such number is the greatest common divisor, written gcd(252, 105).
Listing all divisors of both numbers works for small numbers and hangs on big ones. Euclid saw a shortcut. Cut the largest squares you can from the rectangle. The leftover strip needs the same tile as the whole floor.
Pick a pair, then press Step. Each step cuts q squares of side b from an a by b rectangle and leaves the remainder strip.
Exact traces. 89 and 55 are neighbouring Fibonacci numbers: every quotient is 1, so the rectangle shrinks as slowly as it can.
Why does the leftover strip keep the answer? Any number that divides a and b also divides a minus a whole number of b's, which is the remainder. Call the remainder of a divided by b a mod b, said "a mod b".
The gcd of a and b equals the gcd of b and a mod b.
Divide a by b. Keep b and the remainder a mod b. Repeat until the remainder is 0. The last nonzero number is the gcd.
252 = 2 × 105 + 42, so gcd(252, 105) = gcd(105, 42). 105 = 2 × 42 + 21, so it is gcd(42, 21). 42 = 2 × 21 + 0, so the gcd is 21. A 21 cm tile fits.
How many steps? Every two steps the remainder at least halves, so the count is at most about 2 log2 b. Lamé's theorem gives the tight bound: neighbouring Fibonacci numbers are the worst case, and the count never exceeds 5 times the digit count of b. The pair 89, 55 takes 9 steps; the bound is 10.
The failure. Symptom: a gcd on two 30-digit numbers never returns. Measure: print the loop count; it grows with the numbers, not with their digits. Fix: replace divisor listing with Euclid; Python's math.gcd runs it.
Chapter 2
Carry two extra columns through Euclid's steps and get the coefficients that build the gcd
You have a 252 ml jug and a 105 ml jug. Pour in and pour out. Can you measure exactly 21 ml? Yes: two full 252s out and five 105s in, because 5 × 105 − 2 × 252 = 21. Extended Euclid finds such counts for any pair.
Call the counts x and y. They may be negative: a negative count means "pour out".
a times x plus b times y equals the gcd of a and b.
Some whole numbers x and y always exist so that x copies of a plus y copies of b make exactly the gcd. This is Bézout's identity; x and y are the Bézout coefficients.
a = 252, b = 105, x = −2, y = 5: 252 × (−2) + 105 × 5 = −504 + 525 = 21, which is gcd(252, 105).
How do you find x and y? Keep a table. Each row holds a remainder r and two numbers s and t with a·s + b·t = r. The first two rows are trivial: a = a·1 + b·0 and b = a·0 + b·1. Each new row uses Euclid's quotient q on all three columns at once:
new = old − q × current, for r, for s and for t
Press Step to add a row. The warm column is Euclid's remainder. The pink columns ride along. The check column must always equal r.
Exact traces. The pair 3120, 17 gives the RSA key of Chapter 6. The pair 22, 14 solves the congruence below.
Worked use: solve 14x ≡ 6 (mod 22), meaning 14x leaves remainder 6 when divided by 22. The table for 22, 14 ends with 22 × 2 + 14 × (−3) = 2, so 14 × (−3) leaves remainder 2. Multiply by 3 to get remainder 6: x = −9, which is 13 after adding 22. Because the gcd is 2, there are two answers below 22: 13 and 13 − 11 = 2. Check: 14 × 13 = 182 = 8 × 22 + 6.
The failure. Symptom: an inverse comes out as −367. Measure: check its sign. Fix: reduce it: −367 mod 3120 = 2753. Python's % always returns a value from 0 to n − 1.
Chapter 3
Do arithmetic on a clock, then find the number that undoes a multiplication
It is 10 o'clock. Five hours later it is 3 o'clock, not 15. A clock keeps only the remainder after dividing by 12. That is modular arithmetic, and 12 is the modulus. We write 15 ≡ 3 (mod 12), said "15 is congruent to 3 mod 12": the two numbers leave the same remainder.
You may reduce after every step and the answer stays the same. So 123 × 456 × 789 mod 1000 needs no 8-digit number: 123 × 456 = 56,088, keep 88; 88 × 789 = 69,432, keep 432. The full product, 44,253,432, also ends in 432.
Division is the hard case. On a clock of n hours, the inverse of a, written a−1, is the number that undoes a multiplication by a.
a times a-inverse is congruent to 1, mod n.
Find the position a−1 on the n-clock that, multiplied by a, lands on 1. It exists only when gcd(a, n) = 1. Extended Euclid finds it: from a·x + n·y = 1, take x mod n.
a = 3, n = 10: 3 × 7 = 21 = 2 × 10 + 1, so a−1 = 7. For a = 4 there is none: 4x is always even, and so is 4x mod 10.
Each arrow sends x to a × x mod n. Drag a. If the arrows reach every position, a has an inverse; the pink arrow is the one that lands on 1.
Exact. On a prime clock every a from 1 to n − 1 has an inverse.
Count the a's that have an inverse. That count is Euler's phi function, φ(n), said "phi of n": how many numbers from 1 to n share no factor with n. φ(10) = 4 (1, 3, 7, 9). For two primes, φ(pq) = pq − p − q + 1 = (p − 1)(q − 1). Drop the q multiples of p and the p multiples of q. Then add back pq, which you dropped twice. φ(3233) = 3120.
The failure. Symptom: code returns 3−1 mod 10 = 1. Measure: multiply back: 3 × 1 is not 1 mod 10. Fix: the shortcut an−2 works only for prime n (Chapter 5); use extended Euclid, or pow(3, -1, 10) in Python, which gives 7.
Chapter 4
Read the exponent's bits and square your way to a power instead of multiplying one factor at a time
RSA raises numbers to powers with hundreds of digits in the exponent. Multiplying by a again and again would take longer than the age of the universe. Squaring is the trick: 7, 72, 74, 78 takes three squarings, and every power of 7 up to 715 is a product of those.
Call the number you raise a, the exponent b and the modulus n. Halve the exponent and square the result. If b is odd, one factor a is left over.
a to the b is congruent to a to the floor of b over 2, squared, times a to the b mod 2, mod n.
Write b in binary. Walk its bits. Keep a base that you square at each bit, and multiply the result by the base when the bit is 1. Each bit costs at most two multiplications.
a = 7, b = 13 = 1101 in binary, n = 11. The bases are 7, 72 ≡ 5, 74 ≡ 3, 78 ≡ 9. The 1-bits pick 7, 3 and 9: 7 × 3 = 21 ≡ 10, then 10 × 9 = 90 ≡ 2. So 713 mod 11 = 2, in 3 squarings and 3 multiplications instead of 12.
Pick a power and press Step. Each step reads one bit, right to left. A 1-bit multiplies the warm result by the base. Then the base squares.
Exact. The second power is the hero's lock. The third returns 1 even though 561 is not prime; Chapter 7 explains why.
Count the work for b = 1000, which is 1111101000 in binary: 10 bits and six 1-bits. That is 9 squarings and 6 multiplications, 15 in all, against 999 one at a time. A 2048-bit exponent costs at most about 4,096.
pythondef mod_exp(a, b, n): # a^b mod n result, base = 1, a % n while b > 0: if b & 1: # this bit is 1 result = result * base % n b >>= 1 if b: base = base * base % n # square for the next bit return result # same as pow(a, b, n)
The failure. Symptom: pow(3, 10**18) % p never finishes. Measure: watch memory climb; the full power has about 4.8 × 1017 digits. Fix: pass the modulus: pow(3, 10**18, p) reduces after every step.
Chapter 5
Follow the powers of a around a clock and see that the loop always closes on 1
Take the powers of 3 on a 7-clock: 3, 2, 6, 4, 5, 1. Then the list repeats. The powers of 2 give 2, 4, 1 and repeat sooner. Every number that has an inverse walks a loop that returns to 1.
The dots are the positions with an inverse. The warm path goes a, a2, a3 and so on until it reaches 1. Change n and a.
Exact. The slider steps only through numbers that share no factor with n.
The length of the loop is the order of a. The order always divides φ(n), the number of dots, so a to the power φ(n) is always 1.
a to the phi of n is congruent to 1 mod n, when the gcd of a and n is 1.
Multiply a by itself φ(n) times on the n-clock. You land on 1. This is Euler's theorem. When n is a prime p, φ(p) = p − 1, and it becomes Fermat's little theorem: ap−1 ≡ 1 (mod p).
n = 12, φ(12) = 4 (the numbers 1, 5, 7, 11). Take a = 5: 52 = 25 ≡ 1, so 54 ≡ 1 too. Take n = 7, a = 3: φ(7) = 6 and 36 = 729 = 104 × 7 + 1.
Why is it true? Multiplying every dot by a only reorders the dots (Chapter 3). So the product of all dots equals aφ(n) times the same product. Cancel that product, which has an inverse, and aφ(n) ≡ 1 is left.
A generator is an a whose loop visits every dot: 3 on the 7-clock, 2 on the 11-clock. Diffie-Hellman key exchange uses one. With p = 23 and generator 5, Alice keeps 6 secret and sends 56 mod 23 = 8. Bob keeps 15 and sends 515 mod 23 = 19. Alice computes 196 mod 23 = 2; Bob computes 815 mod 23 = 2. Both hold 2, and the eavesdropper saw only 8 and 19.
The failure. Symptom: the eavesdropper finds the shared secret. Measure: count the possible secret exponents: with p = 23 there are 22 to try. Fix: use a prime so large that walking the loop to find the exponent, the discrete logarithm, is out of reach.
Chapter 6
Build a key pair from two primes, lock with one power, unlock with another, and prove it works
Bob wants strangers to send him secrets. RSA (Rivest, Shamir and Adleman, 1977) lets him publish a public key that locks messages and keep a private key that unlocks them. The recipe uses only Chapters 1 to 5.
To lock a message m (a number from 0 to n − 1), compute c = me mod n. To unlock, compute cd mod n. Both use repeated squaring.
Pick p and q. The purple values are secret, the blue ones public. Drag the message and watch it lock to c and come back.
Toy keys with e = 17. Real keys use primes hundreds of digits long and pad the message first (see below).
Why does unlocking return m? Because e·d leaves remainder 1 when divided by φ(n). Here 17 × 2753 = 46,801 = 15 × 3120 + 1.
m to the e times d is congruent to m mod n, when e times d is congruent to 1 mod phi of n.
Write e·d as 1 + k·φ(n). Then me·d is m times (mφ(n))k. Euler says mφ(n) ≡ 1, so what remains is m.
m = 65: 6517 mod 3233 = 2790. Then 27902753 mod 3233 = 65. Here e·d = 46,801 and k = 15.
Euler needs gcd(m, n) = 1. CLRS covers the other case too: the same argument works mod p and mod q separately, and Chapter 9 glues the two together.
The failure. Symptom: a key falls in one step. Measure: check how close p and q are. If n = 101 × 103 = 10,403, then 1022 − 10,403 = 1 = 12, so n = (102 − 1)(102 + 1). This is Fermat's factoring method. Fix: pick p and q at random and far apart.
Also pad the message with random bytes before locking (OAEP, in PKCS #1, RFC 8017). Plain RSA locks the same message to the same c every time.
Chapter 7
Test a number for primality without factoring it, then meet the composites that pass anyway
RSA needs primes of about 1024 bits. You find one by guessing. Near N, about one integer in ln N is prime, the prime number theorem. For N = 21024 that is one in 710, or one odd number in 355. So you test a few hundred odd candidates, and each test must be fast.
Trial division is no use at this size. Fermat's little theorem gives a test in reverse: if n is prime, then an−1 ≡ 1 (mod n) for every a from 1 to n − 1. So pick a base a and compute an−1 mod n by repeated squaring. If the answer is not 1, n is certainly composite. If it is 1, n is probably prime. This is the Fermat test.
Each square is one base a. Green squares pass on a prime. Red squares pass on a composite: they are liars. Grey squares fail and so prove n composite.
Exact counts over bases 1 to n − 1. Bases that share a factor with n always fail.
Worked number: n = 91 = 7 × 13. Base 2 gives 290 mod 91 = 64, not 1, so 91 is composite. Base 3 or 9 would have said "probably prime": 36 of the 90 bases lie. A random base catches 91 more often than not.
Some composites lie for every base that has an inverse. These are Carmichael numbers. The smallest is 561 = 3 × 11 × 17, and all 320 bases with an inverse pass. Korselt's criterion says why: n has no repeated prime factor, and p − 1 divides n − 1 for every prime p in n. Here 2, 10 and 16 all divide 560, so a560 ≡ 1 mod 3, mod 11 and mod 17 at once.
The failure. Symptom: a key generator accepts 561 as prime. Measure: run the test with many random bases; it still says prime. Fix: look at the path to the final 1, not only at the final 1. That is Miller-Rabin, next.
Chapter 8
Watch the squarings that lead to a to the n minus 1 and catch a square root of 1 that a prime cannot have
On a prime clock, only 1 and −1 square to 1. On 561 there is another: 672 = 4489 = 8 × 561 + 1. Such an extra root is a proof that n is composite.
If x squared is congruent to 1 mod p, then x is congruent to 1 or to minus 1 mod p.
x2 − 1 = (x − 1)(x + 1). If a prime p divides that product, it divides one factor, so x is 1 or −1. Find any other root and n is not prime.
p = 7: the squares of 1 to 6 are 1, 4, 2, 2, 4, 1. Only 1 and 6 (that is, −1) square to 1. On 561, 67 squares to 1, so 561 is composite.
Miller-Rabin hunts for such a root. Split n − 1 into a power of two times an odd number: n − 1 = 2s·d, with s the count of halvings and d odd. Compute ad, then square it s times to reach an−1. A prime gives a chain that starts at 1 or hits −1 before the end. Anything else proves n composite, and a is a witness. A base that passes on a composite is a strong liar.
Pick n and drag the base a. The chain runs from ad to an−1. The strip below marks every base: red bases are strong liars. Press Run rounds to test with random bases.
Exact chains. The strip covers bases 2 to n − 2 (for 104729 it is not drawn). Random bases come from the browser's random generator.
Worked number: n = 561, so 560 = 24 × 35. With a = 2: 235 mod 561 = 263, then 166, then 67, then 1. The step from 67 to 1 finds a root of 1 that is not ±1. Composite. Now n = 2047 = 23 × 89 and a = 2: 2046 = 2 × 1023 and 21023 mod 2047 = 1. Base 2 lies. Base 3 gives 1565, then 1013: no −1, composite.
How often can it lie? For an odd composite n, at most a quarter of the bases are strong liars (Monier and Rabin, 1980). CLRS proves a half. With k random bases the error is at most (1/4)k: about 8 × 10−25 for k = 40.
pythonimport random def miller_rabin(n, k=40): if n < 4: return n in (2, 3) if n % 2 == 0: return False s, d = 0, n - 1 while d % 2 == 0: s, d = s + 1, d // 2 # n-1 = 2^s * d, d odd for _ in range(k): x = pow(random.randrange(2, n - 1), d, n) if x in (1, n - 1): continue for _ in range(s - 1): x = x * x % n if x == n - 1: break else: return False # a witness: certainly composite return True # probably prime
The failure. Symptom: a test with the fixed base 2 calls 2047 prime. Measure: run 2047 through it. Fix: use random bases, or a proven fixed set: the twelve primes 2 to 37 decide every n below 264 (OEIS A014233). AKS (Agrawal, Kayal and Saxena, 2002) never errs and runs in polynomial time, but it is far slower.
Chapter 9
Rebuild a number from its remainders, and split one big computation into small ones
A puzzle from the Sunzi Suanjing: a number leaves 2 when divided by 3, 3 when divided by 5, and 2 when divided by 7. What is it? The answer is 23, and 23 + 105 = 128 also works, because 105 = 3 × 5 × 7.
The Chinese remainder theorem (CRT) says: if the moduli share no factor pairwise, the remainders fix exactly one number from 0 to their product minus 1. Each remainder is a coordinate, and the number is the point.
The cell at column x mod m1, row x mod m2 holds x. Drag x. With coprime moduli every cell fills once. With 4 and 6, half the cells stay empty.
Exact. Red cells are remainder pairs that no x can produce.
To build the number, call the moduli mi, their product M, and the remainders ai. Let Mi = M / mi, the product of the other moduli, and yi its inverse mod mi.
x equals the sum over i of a-i times big-M-i times y-i, all mod big M.
Each term Mi·yi is 1 mod mi and 0 mod every other modulus. So ai times it sets one remainder and leaves the others alone. Add the terms and reduce mod M.
M = 105. M1 = 35, y1 = 2; M2 = 21, y2 = 1; M3 = 15, y3 = 1. x = 2·35·2 + 3·21·1 + 2·15·1 = 140 + 63 + 30 = 233, and 233 mod 105 = 23.
RSA uses CRT to unlock faster. Work mod p and mod q, each half the size of n, then glue. For c = 2790: d mod 60 = 53 and d mod 52 = 49, so mp = 279053 mod 61 = 4 and mq = 279049 mod 53 = 12. With 53−1 mod 61 = 38, h = 38 × (4 − 12) mod 61 = 1 and m = 12 + 1 × 53 = 65. Each half has half the exponent bits and a quarter of the cost per multiplication, so the two halves together cost about a quarter.
The failure. Symptom: a solver finds no x for x ≡ 1 (mod 4) and x ≡ 2 (mod 6). Measure: gcd(4, 6) = 2; the first says x is odd, the second says x is even. Fix: check that the moduli are pairwise coprime before using the formula.
Chapter 10
Keep the tools, the numbers, the checks and the core code on one page
Number-theoretic algorithms work on numbers with hundreds of digits, so their cost counts bits, not size. Euclid and repeated squaring take steps in proportion to the bits. Miller-Rabin uses repeated squaring to test primes. RSA rests on all of them, and on factoring staying slow.
| Tool | Gives | Cost (k-bit inputs) | Used for |
|---|---|---|---|
| Euclid | gcd(a, b) | O(k) divisions | coprime checks, fractions |
| Extended Euclid | gcd, x, y with ax + by = gcd | O(k) divisions | inverses, the RSA private key |
| Repeated squaring | ab mod n | at most 2k multiplications | RSA, Diffie-Hellman, prime tests |
| Miller-Rabin | composite (proof) or probably prime | k rounds of repeated squaring | finding primes for keys |
| CRT | x from its remainders | one inverse per modulus | fast RSA unlocking |
| Term | Meaning | Number on this page |
|---|---|---|
| gcd | largest common divisor | gcd(252, 105) = 21 in 3 steps |
| Bézout coefficients | x, y with ax + by = gcd | 252 × (−2) + 105 × 5 = 21 |
| Inverse a−1 mod n | a · a−1 ≡ 1 | 3−1 mod 10 = 7 |
| φ(n) | count of 1 to n coprime to n | φ(3233) = 3120 |
| Repeated squaring | one squaring per bit, one multiplication per 1-bit | 713 mod 11 = 2 |
| RSA toy key | (n, e) public, d private | n = 3233, e = 17, d = 2753; 65 → 2790 → 65 |
| Carmichael number | fools the Fermat test for every coprime base | 561 = 3 × 11 × 17 |
| Strong liar | a base Miller-Rabin wrongly passes | base 2 on 2047; 8 of 558 bases on 561 |
| CRT | one number from coprime remainders | (2, 3, 2) mod (3, 5, 7) → 23 |
pow.pythondef egcd(a, b): # returns (g, x, y) with a*x + b*y = g old_r, r, old_s, s, old_t, t = a, b, 1, 0, 0, 1 while r: q = old_r // r old_r, r = r, old_r - q * r old_s, s = s, old_s - q * s old_t, t = t, old_t - q * t return old_r, old_s, old_t def inverse(a, n): g, x, _ = egcd(a, n) if g != 1: raise ValueError("no inverse") return x % n def crt(rems, mods): # mods pairwise coprime M = 1 for m in mods: M *= m return sum(a * (M // m) * inverse(M // m, m) for a, m in zip(rems, mods)) % M p, q, e = 61, 53, 17 # toy RSA n, phi = p * q, (p - 1) * (q - 1) d = inverse(e, phi) # 2753 c = pow(65, e, n) # 2790 assert pow(c, d, n) == 65 and crt([2, 3, 2], [3, 5, 7]) == 23
Hashing mod a prime spreads keys over a table (CLRS 11). Rabin-Karp matches strings with a rolling hash mod a prime (CLRS 32). The FFT has an exact twin that works mod a prime (CLRS 30). Whether factoring is hard is still open (CLRS 34).
On key sizes, NIST SP 800-57 Part 1 (Rev. 5) rates a 2048-bit RSA key at 112 bits of security and 3072 bits at 128. Shor's algorithm would factor fast on a large quantum computer. In 2024 NIST published new standards that do not rest on factoring (FIPS 203, 204 and 205).
Now press Present or Teach. Explain from memory why the gcd survives a remainder step, how extended Euclid gives an inverse, why med returns m, and how 67 exposes 561. Then go back to the hero, drag the key size to 2048, and say which chapter makes each bar short or long.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 31, Number-Theoretic Algorithms (third edition numbering). The algorithms and proofs follow the book; the examples, devices and counts are our own and checked by script. Other facts: T. Kleinjung et al., "Factorization of a 768-bit RSA modulus" (CRYPTO 2010); NIST SP 800-57 Part 1 Rev. 5 (2020); NIST FIPS 203, 204 and 205 (2024); RFC 8017 (PKCS #1 v2.2); the strong pseudoprime bounds in OEIS A014233.