Sub topic 12
Fast Exponentiation by Repeated Squaring
This chapter assumes you can trace recursive functions, read Big-O notation, and apply the master theorem from the earlier chapter.
The naive approach
Computing x^n by multiplying x by itself n times takes n − 1 multiplications. For n around a billion, as in cryptography, that is far too slow. Divide and conquer cuts the count to about 2·log₂ n.
The key identity
Any power can be split in half:
- If n is even, x^n = (x^(n/2))².
- If n is odd, x^n = (x^(n/2))² · x, using integer division for n/2.
Each step makes one subproblem of half the size. The combine step is one or two multiplications.
| Step | Work in this algorithm |
|---|---|
| Divide | Compute n // 2 |
| Conquer | Recursively compute x^(n // 2) |
| Combine | Square the result, and multiply by x if n is odd |
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)) # 1594323Running time
The recurrence is T(n) = T(n/2) + O(1). In master theorem terms, a = 1, b = 2, and f(n) = O(1) = Θ(n^(log₂ 1)). That is case 2, so T(n) = O(log n) multiplications.
The common mistake
Speed comes from reusing the result of a single subproblem. The answer to x^(n/2) is all the combine step needs, so there is no reason to compute it twice.
Modular exponentiation
In practice you usually need x^n mod m. If you reduce after every multiplication, the numbers stay smaller than m², so each multiplication has bounded cost. Python's built-in pow(x, n, m) does the same thing.
def power_mod(x, n, m):
# Computes (x ** n) % m for integers n >= 0 and m >= 1
if n == 0:
return 1 % m
half = power_mod(x, n // 2, m)
result = (half * half) % m
if n % 2 == 1:
result = (result * x) % m
return result
print(power_mod(2, 10, 1000)) # 24
print(power_mod(7, 10**18, 13) == pow(7, 10**18, 13)) # TrueThe recursion depth is about log₂ n, so even n = 10^18 needs only about 60 calls. That stays well under Python's recursion limit.
Exercise
How many multiplications does power(x, 13) perform, counting each * operator that runs? Compare this with the naive method.
Show answer
The exponents visited are 13, 6, 3, 1, 0. The base case does no multiplications. n = 1 does 2 (halfhalfx), n = 3 does 2, n = 6 does 1, and n = 13 does 2, for 7 in total. The naive method needs 12.
Exercise
A colleague writes power(x, n) as x * power(x, n - 1). Write its recurrence and running time, and explain why it is not divide and conquer in the useful sense.
Show answer
T(n) = T(n − 1) + O(1), which gives O(n). The subproblem shrinks by a constant instead of a constant fraction, so the recursion depth is n rather than log n and there is no speedup.