Sub topic 8
Fibonacci and the Cost of Repeated Work
Factorial makes one recursive call per step, so its recursion tree is a single chain. Fibonacci makes two calls per step. That one change turns a short, direct definition into a function whose running time grows exponentially. This chapter shows where that cost comes from, how to count it exactly, and which mistakes make it worse.
The chapter assumes you can read Python functions, know Big-O notation, and have seen recursion trees and the call stack in earlier chapters.
The definition and its direct translation
The Fibonacci numbers are defined by a recurrence with two base cases:
- F(0) = 0
- F(1) = 1
- F(n) = F(n − 1) + F(n − 2) for n ≥ 2
The sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. You can translate the definition into code almost word for word:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55The test n < 2 covers both base cases at once, because fib(0) returns 0 and fib(1) returns 1. Every call with n ≥ 2 makes two smaller calls, and each of those calls is at least 1 smaller than n, so every chain of calls reaches a base case.
This function is correct. It is also very slow. fib(30) takes a noticeable fraction of a second, fib(40) takes tens of seconds in CPython, and fib(50) would run for hours.
Drawing the recursion tree
To see why it is slow, draw the calls that fib(5) makes. Each node is one call, and its children are the two calls it makes.
The tree has 15 nodes, so fib(5) makes 15 calls to produce the answer 5. The whole fib(3) subtree appears twice, fib(2) appears three times, and fib(1) appears five times. The function has no memory of earlier calls. Every time it needs fib(3), it recomputes it from scratch.
This is the central problem. The function only has n + 1 distinct subproblems, fib(0) through fib(n), but it solves many of them over and over.
Counting the calls exactly
You can measure the repetition by instrumenting the function with a counter:
from collections import Counter
calls = Counter()
def fib_counted(n):
calls[n] += 1
if n < 2:
return n
return fib_counted(n - 1) + fib_counted(n - 2)
print(fib_counted(5)) # 5
print(sorted(calls.items())) # [(0, 3), (1, 5), (2, 3), (3, 2), (4, 1), (5, 1)]
print(sum(calls.values())) # 15The per-argument counts are 1, 1, 2, 3, 5 for fib(5) down to fib(1). They are Fibonacci numbers themselves. In general, while computing fib(n), the call fib(k) runs F(n − k + 1) times for 1 ≤ k ≤ n, and fib(0) runs F(n − 1) times.
A recurrence for the total
Let C(n) be the total number of calls made by fib(n), counting the top call. A base case makes one call. Any other call makes itself plus all the calls of its two children:
- C(0) = 1
- C(1) = 1
- C(n) = 1 + C(n − 1) + C(n − 2) for n ≥ 2
Add 1 to both sides of the recursive case and you get C(n) + 1 = (C(n − 1) + 1) + (C(n − 2) + 1). So C(n) + 1 follows the Fibonacci recurrence, starting from 2 and 2. That gives the closed form:
C(n) = 2·F(n + 1) − 1
Check it against the tree: F(6) = 8, and 2·8 − 1 = 15. You can also check it in code:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
def call_count(n):
if n < 2:
return 1
return 1 + call_count(n - 1) + call_count(n - 2)
for n in range(11):
assert call_count(n) == 2 * fib(n + 1) - 1
print("formula holds for n = 0..10")The table shows how quickly the count grows.
| n | F(n) | Calls made by fib(n) |
|---|---|---|
| 5 | 5 | 15 |
| 10 | 55 | 177 |
| 20 | 6,765 | 21,891 |
| 30 | 832,040 | 2,692,537 |
| 40 | 102,334,155 | 331,160,281 |
| 50 | 12,586,269,025 | 40,730,022,147 |
The number of calls is roughly twice the answer. Since the answer itself grows exponentially, so does the work.
How fast exponential is
F(n) is close to φⁿ / √5, where φ = (1 + √5) / 2 ≈ 1.618 is the golden ratio. Because C(n) = 2·F(n + 1) − 1, the running time is Θ(φⁿ), about Θ(1.618ⁿ).
You will often see the bound O(2ⁿ). It is true, because each call branches at most twice and the tree is at most n levels deep, but it is not tight. The tight lower bound is easy to sketch too: C(n) > 2·C(n − 2), because fib(n) calls fib(n − 1), which itself calls fib(n − 2), and it also calls fib(n − 2) directly. Doubling every two levels gives at least 2^(n/2) ≈ 1.414ⁿ. The true rate of 1.618ⁿ lies between the two bounds.
In practice, each increase of n by 1 multiplies the time by about 1.618, and each increase by 5 multiplies it by about 11. You can see this with a timing experiment. Exact times depend on your machine, but the ratios should be close to 11:
import time
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
previous = None
for n in (20, 25, 30):
start = time.perf_counter()
fib(n)
elapsed = time.perf_counter() - start
ratio = f" ratio {elapsed / previous:.1f}" if previous else ""
print(f"fib({n}): {elapsed:.4f} s{ratio}")
previous = elapsedTime is the problem, not stack depth
The tree for fib(n) is wide, but its depth is only n. The longest chain is the leftmost path, fib(n) → fib(n − 1) → … → fib(1). At any moment the call stack holds only the frames on one root-to-leaf path. Once fib(n − 1) returns, its frames are popped before fib(n − 2) starts.
So naive Fibonacci uses O(n) stack space and Θ(φⁿ) time. With CPython's default recursion limit of about 1000, fib(900) would not overflow the stack, but it would never finish. Contrast this with factorial, where the time was fine and the stack depth was the limit you hit first.
| Function | Calls per step | Total calls | Maximum stack depth |
|---|---|---|---|
| factorial(n) | 1 | n + 1 | n + 1 |
| fib(n), naive | 2 | 2·F(n + 1) − 1 | n |
Common errors and edge cases
Wrong base cases
If you write only one base case, some calls step past it:
def fib_broken(n):
if n == 1:
return 1
return fib_broken(n - 1) + fib_broken(n - 2)fib_broken(2) calls fib_broken(0), which calls fib_broken(-1), and so on downward until Python raises RecursionError. A recurrence that reaches back two steps needs two base cases, or a single test such as n < 2 that covers both.
Shifted indexing
Writing if n <= 1: return 1 gives the sequence 1, 1, 2, 3, 5, …, which is F(n + 1), not F(n). Both conventions appear in textbooks and puzzles. Decide which one your specification uses and test the first few values, such as fib(0) == 0 and fib(1) == 1.
Invalid input
The n < 2 test also catches inputs it was never meant for. fib(-3) returns −3 instead of reporting an error, and fib(2.5) returns a float. If the function sits at a boundary where callers may pass bad values, validate them:
def fib(n):
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55This version checks its input on every recursive call, which is wasteful. A common pattern is to validate once in a public wrapper and recurse in a private helper.
Large values
Python integers have arbitrary precision, so F(n) never overflows. In languages with fixed-width integers, F(93) is the largest Fibonacci number that fits in a signed 64-bit integer. With the naive algorithm you would run out of time long before that, but the faster methods in the next chapters reach that limit easily.
What the analysis points to
The recursion tree has Θ(φⁿ) nodes but only n + 1 distinct labels. All the extra work comes from solving the same subproblem again. That points to the fix: compute each fib(k) once and reuse the answer. The next chapter does this with memoization, which caches results top-down. The chapter after that builds the values bottom-up with a loop.
Exercise
Using the formula C(n) = 2·F(n + 1) − 1, how many calls does naive fib(8) make, and how many of those are calls to fib(2)?
Show answer
F(9) = 34, so fib(8) makes 2·34 − 1 = 67 calls. The call fib(k) runs F(n − k + 1) times, so fib(2) runs F(8 − 2 + 1) = F(7) = 13 times.
Exercise
A "tribonacci" function is defined by T(0) = 0, T(1) = 0, T(2) = 1, and T(n) = T(n − 1) + T(n − 2) + T(n − 3). Write the naive recursive version, and state its maximum stack depth and whether its running time is polynomial or exponential.
Show answer
def trib(n): return n // 2 if n < 3 else trib(n - 1) + trib(n - 2) + trib(n - 3). The test n < 3 covers all three base cases (0 // 2 = 0, 1 // 2 = 0, 2 // 2 = 1). The stack depth is about n, along the trib(n - 1) chain. The running time is exponential, because each call branches three ways and the same subproblems repeat, giving growth of about 1.839ⁿ.
Exercise
Someone argues that naive fib(1000) fails because it overflows the call stack. Is that the real problem? Explain.
Show answer
Not mainly. The maximum stack depth is about n = 1000, which sits right at CPython's default limit of about 1000, so the call may raise RecursionError. Raising the limit slightly would fix that. The real obstacle is time: the function would make about 2·F(1001) calls, a number with more than 200 digits, so it would never finish.