Modular Exponentiation
Statement
For any natural numbers , , , modular exponentiation via square-and-multiply satisfies:
where is defined by the recurrence:
This replaces multiplications with — essential for RSA and Diffie–Hellman where has hundreds of digits.
Visualization
Compute via square-and-multiply. Binary of , process bits left-to-right:
Exponent bits of 13: 1 1 0 1
| | | |
Step 0: result = 1
Bit 1 (MSB): result = (1^2 * 7) % 11 = 7
Bit 1: result = (7^2 * 7) % 11 = (49*7)%11 = 343%11 = 2
Bit 0: result = (2^2) % 11 = 4%11 = 4
Bit 1 (LSB): result = (4^2 * 7) % 11 = (16*7)%11 = 112%11 = 2
| Bit | Square | Multiply? | Result mod 11 |
|---|---|---|---|
| 1 | yes: | ||
| 1 | yes: | ||
| 0 | no | ||
| 1 | yes: |
Result: . Verify: and .
Proof Sketch
-
Invariant. Let be the running result and the current base. At each step and the product of and the "remaining" exponent gives .
-
Even case. If the current bit is : the result stays unchanged, the base squares. The invariant is maintained because .
-
Odd case. If the current bit is : multiply by the base. Invariant maintained because .
-
Termination. The exponent halves at each step; after steps the exponent is and .
Connections
Modular exponentiation is the computational engine of RSA CorrectnessRSA CorrectnessDecryption recovers the plaintext: m^(ed) ≡ m (mod n) whenever ed ≡ 1 (mod φ(n)).Read more → and Diffie–HellmanDiffie–HellmanAlice and Bob derive the same shared secret g^(ab) from public keys g^a and g^b in any commutative group.Read more →. Its cost is what makes these systems practical. The correctness of the recurrence is an instance of Fundamental Theorem of ArithmeticFundamental Theorem of ArithmeticEvery integer greater than 1 has a unique prime factorizationRead more → — binary representation — applied to the exponent.
Lean4 Proof
/-- Lean's core library provides Nat.pow_mod for efficient modular
exponentiation (square-and-multiply). It satisfies:
Nat.pow_mod a n m = a^n % m
This is definitionally true in Lean 4 core. -/
-- Concrete verification: 7^13 mod 11 = 2
example : 7 ^ 13 % 11 = 2 := by decide
-- Nat.pow_mod gives the same answer (square-and-multiply algorithm)
example : Nat.pow_mod 7 13 11 = 2 := by decide
-- Square-and-multiply intermediate steps for 7^13 mod 11
-- Step trace: bits of 13 = 1101, result builds as 7→2→4→2
example : 7 ^ 1 % 11 = 7 := by decide
example : 7 ^ 2 % 11 = 5 := by decide
example : 7 ^ 4 % 11 = 3 := by decide
example : 7 ^ 8 % 11 = 9 := by decide
example : 7 ^ 13 % 11 = 2 := by decide -- 13 = 8+4+1, so 9*3*7 mod 11 = 2Referenced by
- One-Way FunctionCryptography