Sub topic 11
Computing Powers with Linear Recursion
This chapter assumes you can write Python functions, read a recursive function with a base case and a recursive case, and trace calls on the call stack. It also assumes basic Big-O notation. Here we apply the factorial pattern to powers. We use only non-negative integer exponents for now. Later chapters make the computation faster and add negative exponents.
The recursive definition
For a number x and an integer n >= 0, the power x to the n is defined by two rules:
- Base case: x⁰ = 1.
- Recursive case: xⁿ = x · xⁿ⁻¹ for n > 0.
Each step lowers the exponent by one, so every chain of calls ends at n == 0. This is the same shape as factorial. Factorial multiplies by a different number at each step (n, then n−1, and so on). The power function multiplies by the same x every time.
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
print(power(2, 10)) # 1024Tracing the calls
A call to power(2, 3) cannot multiply anything until it gets back the result of power(2, 2). That call in turn waits on power(2, 1). Pending frames pile up on the stack until the base case returns 1. Then the multiplications happen one at a time as the frames return.
Counting the work
Each non-base call does exactly one multiplication. Computing xⁿ therefore takes n multiplications and makes n + 1 calls, which is O(n) time. The stack holds up to n + 1 frames at once, so the function also uses O(n) space. You can confirm the count by having the function return it alongside the value:
def power_count(x, n):
if n == 0:
return 1, 0
value, mults = power_count(x, n - 1)
return x * value, mults + 1
print(power_count(2, 10)) # (1024, 10)
print(power_count(5, 3)) # (125, 3)The recursion tree for this function is a single chain with no branching. Recursion of this kind is called linear recursion. Unlike naive Fibonacci, it never recomputes anything. Its cost comes from the number of steps, and the steps are not wasted.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Base case `n == 1` returning `x` | `power(x, 0)` never reaches the base case and recurses forever | Use `n == 0` returning `1` |
| Passing a negative `n` | `n` moves away from 0, and the result is `RecursionError` | Reject `n < 0` or handle it separately |
| Passing a float such as `2.5` | `n` goes 2.5, 1.5, 0.5, -0.5 and never equals 0 | Require an integer exponent |
| Large `n`, such as 5000 | The stack depth exceeds Python's limit of about 1000 | Use a loop or a faster algorithm |
A guarded version validates its input at the boundary:
def safe_power(x, n):
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
if n == 0:
return 1
return x * safe_power(x, n - 1)
print(safe_power(3, 4)) # 81Exercise
How many multiplications does power(3, 5000) perform, and what happens when you run it in a default CPython session?
Show answer
It would perform 5000 multiplications, but it needs about 5001 nested frames. That is far above CPython's default recursion limit of about 1000, so it raises RecursionError before finishing.
Exercise
Write power_iter(x, n) that gives the same results as power for n >= 0, using a loop instead of recursion. What is its space usage?
Show answer
def power_iter(x, n): then result = 1, then for _ in range(n): result *= x, then return result. It still does n multiplications (O(n) time), but it uses O(1) extra space because it never stacks frames.