Sub topic 12
Exponentiation by Squaring
This chapter assumes you have read the earlier chapter on linear recursive power. It also assumes you can read a recursion tree, know that // is integer division and % is remainder in Python, and can reason with Big-O notation. Here we cut the cost of computing x ** n from n multiplications down to roughly 2 log₂ n.
The Idea: Halve the Exponent
The linear version used the rule xⁿ = x · xⁿ⁻¹. Each call reduces the exponent by one, so computing x¹⁰⁰⁰ takes 1000 multiplications and 1000 stack frames.
A better rule splits the exponent in half:
- If
nis even,xⁿ = (x^(n/2))². - If
nis odd,xⁿ = (x^((n−1)/2))² · x. - If
nis 0,x⁰ = 1.
Integer division covers both cases. For even n, n // 2 equals n/2. For odd n, n // 2 equals (n−1)/2. So each call makes one recursive call on n // 2 and then squares the result, multiplying by x once more when n is odd.
This is divide and conquer. The problem shrinks by a constant factor at each step, not by a constant amount. That difference turns linear work into logarithmic work.
The Recursive Implementation
This version handles non-negative integer exponents. The next chapter extends it to negative ones.
def fast_power(x, n):
if n == 0:
return 1
half = fast_power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(fast_power(2, 10)) # 1024
print(fast_power(3, 5)) # 243
print(fast_power(7, 0)) # 1The function has one base case, n == 0, and one recursive case, which always calls itself on n // 2. The important detail is that half is computed once and stored in a variable. The function then multiplies half by itself. This one detail is what makes the algorithm fast, as the section on common errors shows.
Tracing a Call
Here is what happens for fast_power(2, 10). The calls go down through exponents 10, 5, 2, 1, 0. The results come back up:
| Call | `n % 2` | `half` returned by the inner call | Result |
|---|---|---|---|
| `fast_power(2, 0)` | base case | — | 1 |
| `fast_power(2, 1)` | 1 (odd) | 1 | 1 · 1 · 2 = 2 |
| `fast_power(2, 2)` | 0 (even) | 2 | 2 · 2 = 4 |
| `fast_power(2, 5)` | 1 (odd) | 4 | 4 · 4 · 2 = 32 |
| `fast_power(2, 10)` | 0 (even) | 32 | 32 · 32 = 1024 |
The recursion tree here is a single path, not a branching tree. The path's length is the number of times you can halve n before reaching 0.
Counting Multiplications
Each call with n > 0 does one squaring, plus one extra multiplication if n is odd. Halving n repeatedly with // is the same as shifting its binary form right by one bit. So:
- The number of non-base calls equals the bit length of
n, which is⌊log₂ n⌋ + 1. - The number of extra multiplications equals the number of 1-bits in
n.
The total is at most 2(⌊log₂ n⌋ + 1) multiplications. You can check this by having the function return its multiplication count along with the result:
def fast_power_counted(x, n):
"""Return (x ** n, number of multiplications performed)."""
if n == 0:
return 1, 0
half, mults = fast_power_counted(x, n // 2)
if n % 2 == 0:
return half * half, mults + 1
return half * half * x, mults + 2
for n in [10, 100, 1000, 10**6]:
value, mults = fast_power_counted(2, n)
assert value == 2 ** n
print(f"n = {n:>7}: {mults} multiplications (linear version: {n})")Output:
n = 10: 6 multiplications (linear version: 10)
n = 100: 10 multiplications (linear version: 100)
n = 1000: 16 multiplications (linear version: 1000)
n = 1000000: 27 multiplications (linear version: 1000000)The recurrence for the running time is T(n) = T(n/2) + O(1), which solves to T(n) = O(log n). The recursion depth is also O(log n). For n = 10⁶ that means about 21 frames, far below Python's default limit of 1000. The linear power(2, 10**6) would raise RecursionError long before finishing.
Why It Is Correct
A short argument by strong induction on n shows the function is correct.
- Base case:
fast_power(x, 0)returns 1, which equalsx⁰. - Inductive step: Assume
fast_power(x, k)returnsxᵏfor everyk < n, wheren ≥ 1. Sincen // 2 < n, the call returnshalf = x^(n//2). Ifnis even,half · half = x^(2·(n//2)) = xⁿ. Ifnis odd,2·(n//2) = n − 1, sohalf · half · x = x^(n−1) · x = xⁿ.
We need strong induction here, not ordinary induction, because the recursive call jumps from n to n // 2 instead of to n − 1. The argument also shows why the recursion terminates. For any n ≥ 1, n // 2 is strictly smaller than n, and it is still non-negative, so the exponent must eventually reach 0.
Common Errors
Calling the Recursive Function Twice
This is the most common mistake. It looks harmless:
def slow_fast_power(x, n):
if n == 0:
return 1
if n % 2 == 0:
return slow_fast_power(x, n // 2) * slow_fast_power(x, n // 2)
return slow_fast_power(x, n // 2) * slow_fast_power(x, n // 2) * x
print(slow_fast_power(2, 10)) # 1024, correct but slowThe answer is correct, but each call now makes two recursive calls. The recurrence becomes T(n) = 2T(n/2) + O(1), which solves to O(n). All the savings are gone, and the function repeats work the same way naive Fibonacci does.
The fix is to store the result in a variable, as half does. You could also cache results with memoization, but that is unnecessary here because the two calls are identical and sit side by side.
Passing a Negative Exponent
In Python, -1 // 2 is -1, because floor division rounds toward negative infinity. If you call fast_power(2, -1), the exponent stays at -1 forever and never reaches the base case. The program eventually raises RecursionError. Either reject negative n with a ValueError or handle it on purpose, as the next chapter does.
Using Floats with Large Exponents
fast_power(1.0001, 10**7) returns a float, and floats overflow to inf or lose precision. Every multiplication can add a little rounding error. Squaring has far fewer multiplications than the linear method, so it usually loses less precision, but it cannot exceed the range of a 64-bit float.
An Iterative Version
The same algorithm can run without recursion. It reads the bits of n from lowest to highest, and squares x at each step:
def fast_power_iter(x, n):
if n < 0:
raise ValueError("n must be non-negative")
result = 1
base = x
while n > 0:
if n % 2 == 1:
result *= base
base *= base
n //= 2
return result
print(fast_power_iter(2, 10)) # 1024
print(fast_power_iter(3, 13)) # 1594323After k passes, base holds x^(2ᵏ), and result holds the product of the x^(2ⁱ) terms whose bits are set among the first k bits of n. This version uses constant stack space. Since the recursion depth is only O(log n), stack depth is not a reason to prefer it. Choose it when you want to avoid function-call overhead, or when the language you use has no convenient recursion.
| Method | Multiplications | Stack depth | Typical use |
|---|---|---|---|
| Linear recursion | n | n | Teaching only |
| Recursive squaring | ≤ 2(⌊log₂ n⌋ + 1) | ⌊log₂ n⌋ + 2 | Clear code, divide and conquer |
| Iterative squaring | ≤ 2(⌊log₂ n⌋ + 1) | 1 | Production code, modular arithmetic |
Python's built-in pow(x, n) and the ** operator already use a squaring algorithm for integers. Write your own when you need a custom multiplication, such as for matrices or modular arithmetic, or when you are learning how the algorithm works.
Exercise
List the exponents passed to fastpower when you call fastpower(3, 13), and give the value each call returns. How many multiplications are performed in total?
Show answer
The calls use exponents 13, 6, 3, 1, 0. The returns are: n=0 gives 1; n=1 gives 113 = 3; n=3 gives 333 = 27; n=6 gives 2727 = 729; n=13 gives 729729*3 = 1594323. The odd exponents 13, 3, and 1 each use 2 multiplications, and 6 uses 1, so the total is 7. This matches the formula: 13 is 1101 in binary, with bit length 4 and three 1-bits, and 4 + 3 = 7.
Exercise
A colleague writes return fast_power(x, n // 2) ** 2 for the even case. Is this still O(log n)? What hidden assumption does the answer depend on?
Show answer
There is only one recursive call, so the recursion still makes O(log n) calls. However, it hands the squaring to Python's operator instead of doing one explicit multiplication. For ints and floats, squaring with 2 costs a constant number of operations, so the bound holds. The code then depends on the very operation we are trying to implement, though, and it fails for a custom type (such as a matrix class) whose * operator is missing or is defined in terms of fast_power itself. Writing half half avoids that dependency.
Exercise
Write the recurrence for slowfastpower and explain why it does exactly as much work as the linear method, up to a constant factor.
Show answer
T(n) = 2T(n/2) + O(1). The recursion tree has depth about log2 n, and level k has 2^k nodes, so the total is about 1 + 2 + 4 + ... + n, which is roughly 2n calls. That is O(n). The same subproblem x^(n//2) is solved twice at every level, and this duplicated work cancels the gain from halving the exponent.