ProgrammingHardTCS NQT · Accenture pattern

Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(5)?

Consider this naive recursive Fibonacci. How many TOTAL calls to fib (including the initial call) happen when computing fib(5)?
Function fib(Integer k)
    [call count += 1 happens here]
    if (k <= 1)
        return k
    end if
    return fib(k - 1) + fib(k - 2)
end Function

fib(5)
  1. A. 9
  2. B. 13
  3. C. 15
  4. D. 17

Correct answer: C. 15

Each call to fib(k) with k > 1 spawns exactly two further calls, fib(k-1) and fib(k-2), down to the base cases. Counting every call in the full recursion tree for fib(5) (value 5) gives 15 total calls — it is NOT simply 2×5-1.

More Pseudocode and Code Tracing questions

Exams that ask this topic