Sub topic 12
Fast Exponentiation by Repeated Squaring
This chapter assumes you can read recursive Python, write a recurrence such as T(n) = T(n/2) + O(1), and apply the master theorem from earlier chapters. You will see how one observation, that x^n = (x^(n/2))², cuts the work of computing a power from n multiplications to about 2 log₂ n.
The Naive Approach and Its Cost
The direct way to compute x^n multiplies x by itself n − 1 times:
def naive_power(x, n):
result = 1
for _ in range(n):
result *= x
return result
print(naive_power(3, 13)) # 1594323That takes Θ(n) multiplications. For n = 13 this is cheap. In cryptography, exponents often have 2048 bits, so n is close to 2^2048 and a loop of that length cannot run to completion. You need an algorithm whose cost grows with the number of digits of n, not with n itself.
The Divide-and-Conquer Idea
Exponents add when you multiply powers: x^a · x^b = x^(a+b). Split n into two halves:
- If n is even, x^n = x^(n/2) · x^(n/2).
- If n is odd, x^n = x^(⌊n/2⌋) · x^(⌊n/2⌋) · x.
The two halves are the same subproblem. You solve it once and square the result. In terms of the paradigm:
| Step | What happens in `power(x, n)` |
|---|---|
| Divide | Reduce the exponent to ⌊n/2⌋ |
| Conquer | Recursively compute `half = x ** (n // 2)` |
| Combine | Return `half * half`, times one extra `x` if n is odd |
| Base case | n = 0 returns 1 |
def power(x, n):
# Computes x ** n for an integer n >= 0
if n == 0:
return 1
half = power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(power(3, 13)) # 1594323The diagram below traces the calls for power(3, 13). The exponent halves at each level, and the results are combined on the way back up.
Correctness by Induction
Use strong induction on n.
- Base:
power(x, 0)returns 1, which equals x^0. - Step: assume
power(x, k)returns x^k for every k < n. Since n ≥ 1, ⌊n/2⌋ < n, sohalfequals x^(⌊n/2⌋). If n is even, half · half = x^(2·n/2) = x^n. If n is odd, n = 2⌊n/2⌋ + 1, so half · half · x = x^n.
Termination follows from the same fact. The exponent strictly decreases and never goes below 0, so the recursion reaches the base case.
Running Time
Each call does a constant number of multiplications and makes one recursive call on ⌊n/2⌋:
T(n) = T(n/2) + O(1)
With a = 1, b = 2, and f(n) = Θ(1), we get n^(log_b a) = n^0 = 1. This matches f(n), so case 2 of the master theorem gives T(n) = Θ(log n). This is the same recurrence as binary search. The recursion depth is ⌊log₂ n⌋ + 2 calls, counting the n = 0 base case. Each level does at most two multiplications, so the total is at most about 2 log₂ n.
For a 2048-bit exponent that comes to about 4096 multiplications, where the naive loop would need 2^2048.
The Most Common Mistake: Recomputing the Half
A version that looks the same but calls the subproblem twice loses the whole speedup:
def slow_power(x, n):
if n == 0:
return 1
if n % 2 == 0:
return slow_power(x, n // 2) * slow_power(x, n // 2)
return slow_power(x, n // 2) * slow_power(x, n // 2) * x
print(slow_power(3, 13)) # 1594323, but with Θ(n) workIts recurrence is T(n) = 2T(n/2) + O(1). Now n^(log₂ 2) = n grows faster than f(n) = 1, so case 1 of the master theorem gives Θ(n). The answer is still correct, which makes the bug easy to miss.
The Iterative Version: Reading the Bits of n
The recursion processes n from its most significant bit downward. An equivalent loop reads the bits from least significant upward. Write n in binary: 13 = 1101₂ = 8 + 4 + 1, so 3^13 = 3^8 · 3^4 · 3^1. The loop keeps squaring x to produce x, x², x⁴, x⁸, … and multiplies into the result the powers whose bit is set.
def power_iter(x, n):
# Computes x ** n for an integer n >= 0, using O(1) extra space
result = 1
while n > 0:
if n & 1:
result *= x
x *= x
n >>= 1
return result
print(power_iter(3, 13)) # 1594323This version uses no call stack. It performs ⌊log₂ n⌋ + 1 squarings and one multiplication for each 1 bit in n. Production libraries usually use this form.
Modular Exponentiation
In practice you usually want x^n mod m. Reducing after every multiplication keeps each intermediate value below m², which is correct because (a · b) mod m = ((a mod m) · (b mod m)) mod m.
def pow_mod(base, exp, mod):
# Computes base ** exp % mod for exp >= 0 and mod >= 1
result = 1 % mod
base %= mod
while exp > 0:
if exp & 1:
result = result * base % mod
base = base * base % mod
exp >>= 1
return result
print(pow_mod(3, 13, 1000)) # 323
print(pow_mod(7, 10**18, 10**9 + 7) == pow(7, 10**18, 10**9 + 7)) # TrueThe 1 % mod handles the edge case mod = 1, where every answer must be 0. Python's built-in pow(base, exp, mod) uses the same algorithm.
It Works for Any Associative Operation
The proof used only one property: multiplication is associative, so it does not matter how you group the factors. The same code therefore raises matrices to a power. The matrix [[1, 1], [1, 0]] raised to the n-th power is [[F(n+1), F(n)], [F(n), F(n−1)]], so you can compute Fibonacci numbers in O(log n) matrix multiplications:
def mat_mult(A, B):
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]],
]
def mat_power(M, n):
result = [[1, 0], [0, 1]] # identity matrix
while n > 0:
if n & 1:
result = mat_mult(result, M)
M = mat_mult(M, M)
n >>= 1
return result
def fib(n):
return mat_power([[1, 1], [1, 0]], n)[0][1]
print(fib(10)) # 55
print(fib(90)) # 2880067194370816120The identity element replaces the 1 in result = 1. Matrix multiplication is not commutative, but that does not matter here because every factor is a power of the same matrix M, and powers of one matrix commute with each other.
Edge Cases and Gotchas
| Situation | What happens | What to do |
|---|---|---|
| n = 0 | Returns 1, including 0^0 = 1 | Accept the convention or reject 0^0 explicitly |
| n < 0 | `n // 2` stays at −1 and the recursion never ends | Validate input, or compute 1 / power(x, −n) for floats |
| Float base | Rounding errors build up over about log n multiplications | Use `math.pow` or accept a small relative error |
| Big integers without a modulus | Each multiplication costs more as the numbers grow | Expect the final squaring to dominate the cost |
| Very large n, recursive form | Depth is only about log₂ n, so the stack is safe | No action needed |
The "O(log n)" bound counts multiplications. It does not count bit operations. Without a modulus, x^n has about n·log₂ x bits, so the final squarings work on huge numbers. With a fixed modulus, every multiplication has bounded cost, and the log n bound describes the real running time.
Exercise
How many multiplications does power_iter(x, 45) perform, counting both the squarings of x and the multiplications into result? Note that the loop also squares x on its last iteration.
Show answer
45 = 101101₂ has 6 bits, 4 of which are 1. The loop runs 6 times, so it performs 6 squarings and 4 multiplications into result, for 10 in total. (The last squaring is wasted. An optimized loop skips it, which gives 9.) The naive loop needs 45.
Exercise
A colleague writes return power(x, n - 1) * x for odd n and half * half for even n. What recurrence describes the worst case, and what is the running time?
Show answer
An odd n leads to n − 1, which is even and then halves. So at most two calls happen per halving, and T(n) ≤ T(n/2) + O(1) over every two levels. The running time is still Θ(log n) with at most about 2 log₂ n calls. The version is correct and fast, just slightly deeper.
Exercise
Why must pow_mod reduce after each multiplication instead of computing power(base, exp) and taking % mod once at the end?
Show answer
Without reduction, the intermediate values grow to about exp·log₂(base) bits. For exp = 10^18 that number cannot be stored. Reducing each step keeps every value below mod², so each multiplication costs a bounded amount and the total work is O(log exp) multiplications.