Practice question · Multiple choice
A recursive Fibonacci function is elegant and unusably slow; the loop version is ugly and instant. Where does the recursive version's time actually go?
Hints
- Draw the call tree for fib(6). Count how many times fib(3) appears.
- Ask how many DISTINCT values fib is ever called with.
Show the answer
C. Into recomputing the same subproblems exponentially often
Why
The tree has about 2ⁿ nodes and only n distinct values in it, so almost all the work is repetition. Adding a cache makes it linear without touching the structure, which is why the fix is memoisation rather than abandoning recursion, and why this is the standard first example of dynamic programming.
Practise Recursion
The app has 6 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Recursion
- A recursive function calls itself, which sounds like it should never finish. Why does a correct recursion…
- Each definition is evaluated at n = 5. Sort by whether the recursion terminates.
- Order what happens when a recursive factorial computes 3 factorial.
- The factorial is defined by fact(n) = n * fact(n-1) with fact(0) = 1. Compute fact(5).
- Computing fact(4) recursively, how many calls to fact are made in total, counting the original call and the…
- Complete the condition for a recursion to terminate.