Sub topic 11
Computing Powers with Linear Recursion
This chapter assumes you can write Python functions, read a recursive function's base case and recursive case, and trace calls on the call stack. You should also know Big-O notation. Earlier chapters used factorial to cover these ideas. Here we apply the same pattern to raising a number to a power. The result is correct but slow, and the next chapter improves on it.
The Recursive Definition of a Power
For a non-negative integer n, the power x^n means multiplying x by itself n times. You can also define it recursively:
- Base case:
x^0 = 1 - Recursive case:
x^n = x · x^(n-1)forn > 0
This has the same shape as factorial. Factorial multiplies by n, then recurses on n - 1. Power multiplies by a fixed x, then recurses on n - 1. Each call reduces the exponent by one until it reaches zero.
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
print(power(2, 10)) # 1024The base case returns 1 because 1 is the identity for multiplication. Multiplying by 1 changes nothing, so the chain of multiplications above it gives the right product. For the same reason, 0! = 1 and an empty product is 1.
Tracing a Call
Trace power(2, 3). Each call waits for the call below it to return before it can do its own multiplication.
power(2, 3)needspower(2, 2).power(2, 2)needspower(2, 1).power(2, 1)needspower(2, 0).power(2, 0)hits the base case and returns1.power(2, 1)returns2 * 1 = 2.power(2, 2)returns2 * 2 = 4.power(2, 3)returns2 * 4 = 8.
All the multiplications happen on the way back up, as the calls unwind. While the base case runs, four frames are on the stack at once.
Counting the Work
This function is called linear recursion because each call makes at most one recursive call. The recursion tree is therefore a chain and has no branches. Compare this with naive Fibonacci, where each call makes two recursive calls and the tree grows exponentially. Here the tree has exactly n + 1 nodes.
You can confirm the multiplication count by returning a counter alongside the value:
def power_counted(x, n):
if n == 0:
return 1, 0
value, mults = power_counted(x, n - 1)
return x * value, mults + 1
for n in [0, 1, 5, 10]:
print(n, power_counted(3, n))
# 0 (1, 0)
# 1 (3, 1)
# 5 (243, 5)
# 10 (59049, 10)The function makes n + 1 calls and performs n multiplications. That costs O(n) time, plus O(n) stack space for the pending frames.
Why It Is Correct
The induction argument from the factorial chapter applies directly. Claim: power(x, n) returns x^n for every integer n ≥ 0.
- Base:
power(x, 0)returns1, which equalsx^0. - Step: assume
power(x, k)returnsx^k. Thenpower(x, k + 1)returnsx * power(x, k) = x · x^k = x^(k+1).
The proof depends on the exponent getting smaller and eventually reaching 0. That observation leads straight to the most common bug.
Common Errors and Edge Cases
Negative exponents never reach the base case
When n is negative, n - 1 moves further away from 0. The base case never fires, and Python stops the program once the stack limit is hit:
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
try:
power(2, -1)
except RecursionError:
print("RecursionError: the exponent never reached 0")A later chapter extends powers to negative exponents properly. For now, reject inputs that the definition doesn't cover:
def power_checked(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 * power_checked(x, n - 1)
print(power_checked(5, 3)) # 125
try:
power_checked(5, -2)
except ValueError as e:
print(e) # n must be a non-negative integerNon-integer exponents
power(4, 0.5) makes the same mistake. 0.5 - 1 is -0.5, then -1.5, and so on, and the value never equals 0. Linear recursion only works for integer exponents. For fractional powers, use x ** 0.5 or math.sqrt.
Zero to the zero
power(0, 0) returns 1. Python's 0 ** 0 and most combinatorics and programming conventions also give 1. Some math contexts leave it undefined, so document the choice if your callers might care.
Deep recursion
Each call uses a stack frame, so the exponent is limited by the recursion limit:
import sys
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
print(sys.getrecursionlimit()) # usually 1000
try:
power(2, 5000)
except RecursionError:
print("Too deep for the default recursion limit")Raising the limit with sys.setrecursionlimit only postpones the problem, and setting it too high can crash the interpreter. A loop has no depth limit:
def power_iter(x, n):
result = 1
for _ in range(n):
result *= x
return result
print(power_iter(2, 10)) # 1024
print(power_iter(2, 5000) == 2 ** 5000) # TrueFloating-point drift
With a float base, every multiplication can round. power(1.1, 3) may not print exactly 1.331. Compare floats with math.isclose instead of ==. The error grows with the number of multiplications, which is one more reason to prefer fewer of them.
Big integers are not constant-cost
Python integers have no size limit, so power(2, 5000) gives an exact 5001-bit number. Multiplying large integers takes longer as they grow, though. The O(n) figure counts multiplications, not machine operations. For big results, the real cost rises faster than linear.
Comparing the Versions
| Version | Multiplications | Extra space | Fails on |
|---|---|---|---|
| `power` (recursive) | n | O(n) stack frames | negative or fractional `n`, `n` near the recursion limit |
| `power_checked` | n | O(n) stack frames | raises `ValueError` on bad `n`, still limited by depth |
| `power_iter` (loop) | n | O(1) | negative `n` returns 1 silently, because the loop body never runs |
| `x ** n` (built-in) | far fewer | O(1) | nothing for ordinary inputs |
The last row shows the gap. Python's built-in ** computes 2 ** 1000000 instantly. A linear method needs a million multiplications. Linear recursion copies the definition faithfully, but it uses none of the structure of exponents. For example, it ignores that x^10 = (x^5)^2. The next chapter uses that identity to cut the work from n multiplications to about log₂ n.
Exercises
Exercise
How many calls to power and how many multiplications does power(7, 4) perform? What is the maximum number of power frames on the stack at once?
Show answer
It makes 5 calls, for n = 4, 3, 2, 1, 0, and 4 multiplications. All 5 frames are on the stack together when power(7, 0) runs. The result is 2401.
Exercise
A student writes the base case as "if n == 1: return x" and removes the n == 0 check. Which inputs now break, and how?
Show answer
power(x, 0) breaks. It calls power(x, -1), then power(x, -2), and so on, and never reaches n == 1, so it raises RecursionError. Inputs with n >= 1 still work. The fix is to keep the n == 0 base case, with or without the n == 1 case.
Exercise
Write sum_powers(x, n), which returns x^0 + x^1 + ... + x^n using linear recursion with a single recursive call per level and no call to power. Hint: x^0 + ... + x^n = 1 + x * (x^0 + ... + x^(n-1)).
Show answer
def sumpowers(x, n): if n == 0: return 1 return 1 + x * sumpowers(x, n - 1) For example, sum_powers(2, 3) returns 1 + 2 + 4 + 8 = 15. It makes n multiplications and recurses to depth n + 1. This is Horner's rule applied to the geometric series.
Exercise
power_iter(2, -3) returns 1 instead of raising an error. Explain why, and say why a silent wrong answer can be worse than the RecursionError from the recursive version.
Show answer
range(-3) is empty, so the loop never runs and result keeps its starting value of 1. The recursive version fails loudly. The loop returns a plausible-looking wrong value that can spread through a program unnoticed. Validate n explicitly in both versions.