Mathematics I / Recursion
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
  1. Draw the call tree for fib(6). Count how many times fib(3) appears.
  2. 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.

Read the lesson: Recursion →

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