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

110100100010k5101520ncount (log scale)
Measured
Table
ncount
49
625
867
10177
12465
141,219
163,193
188,361
2021,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
  1. calls(n) = 1 + calls(n − 1) + calls(n − 2), the Fibonacci recurrence plus one.
  2. So calls(n) = 2·F(n + 1) − 1, which grows like φⁿ with φ = (1 + √5)/2 ≈ 1.618.
  3. 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).