Exercise 15 of 30 · intermediate · recursion · exponential · recursion tree
Naive recursive Fibonacci
The code
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)How many calls does fib(n) make?
Count: calls.
Measured counts
Table
| n | count |
|---|---|
| 4 | 9 |
| 6 | 25 |
| 8 | 67 |
| 10 | 177 |
| 12 | 465 |
| 14 | 1,219 |
| 16 | 3,193 |
| 18 | 8,361 |
| 20 | 21,891 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(φⁿ) ≈ Θ(1.618ⁿ), within O(2ⁿ)
- Extra space
- Θ(n) call stack
- Exact count
- 2·F(n+1) − 1 calls
- calls(n) = 1 + calls(n − 1) + calls(n − 2), the Fibonacci recurrence plus one.
- So calls(n) = 2·F(n + 1) − 1, which grows like φⁿ with φ = (1 + √5)/2 ≈ 1.618.
- The deepest path is n calls long: Θ(n) stack space. Memoization (M11, M32) makes it Θ(n) time.
Common mistake: Answering exactly Θ(2ⁿ). 2ⁿ is an upper bound; the tight bound is φⁿ because the right subtree is smaller.
Check: measured count ÷ (2ⁿ) settles near 0.0209 for large n (growth factors are compared for exponential classes).