Sub topic 3
Bottom-Up Fibonacci with a Loop
This chapter assumes you know Python functions and loops, integer division (//) and remainder (%), and Big-O notation. It also assumes you have seen memoized Fibonacci.
Bottom-Up Fibonacci
Memoization still recurses, so it uses stack depth proportional to n. A bottom-up loop starts from the base cases and builds upward. Each Fibonacci number depends only on the two before it, so the loop keeps just those two values.
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_iter(10)) # 55This runs in O(n) time with O(1) extra space and has no recursion depth limit.
Linear Recursive Power
The definition xⁿ = x · xⁿ⁻¹ with x⁰ = 1 translates directly into code:
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
print(power(2, 10)) # 1024It makes n multiplications and n nested calls. Large n hits Python's recursion limit.
Exponentiation by Squaring
You can halve the exponent at each step. For even n, xⁿ = (x^(n/2))². For odd n, one extra factor of x is needed. Because each call halves n, the function makes O(log n) calls.
def fast_power(x, n):
if n < 0:
return 1 / 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(2, -2)) # 0.25Negative Exponents
The first branch of fast_power uses x⁻ⁿ = 1 / xⁿ. The result is a float, and x = 0 with a negative n raises ZeroDivisionError.
Modular Exponentiation
In cryptography you often need xⁿ mod m for very large n. If you reduce every intermediate result modulo m, the numbers stay smaller than m².
def mod_power(x, n, m):
if n == 0:
return 1 % m
half = mod_power(x, n // 2, m)
result = (half * half) % m
if n % 2 == 1:
result = (result * x) % m
return result
print(mod_power(3, 200, 13)) # 9
print(pow(3, 200, 13)) # 9Python's built-in three-argument pow uses the same method.
Exercise
How many recursive calls does fast_power(x, 16) make, including the first call, and how many does power(x, 16) make?
Show answer
fast_power is called with n = 16, 8, 4, 2, 1, 0, which is 6 calls. power is called with n = 16 down to 0, which is 17 calls.
Exercise
Why does fibiter avoid the RecursionError that fibmemo(5000) can raise?
Show answer
fibiter uses a loop that runs in a single stack frame. fibmemo makes nested calls about n levels deep, which goes past CPython's default limit of about 1000 frames.