Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Count how many calls the recursive fibonacci(n) makes for . What do you notice?
Two recursive calls in every call make the number of calls explode.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
The counts are , , and .
When grows by 5, the number of calls grows about eleven times. The function works out the same small values again and again. For , it would need hundreds of millions of calls.
A loop that keeps the last two numbers needs only steps. (Programmers also use a trick called memoisation: remember the answers that are already worked out.)
Log in to join the discussion.
Loading…
With Standard, you also open 10 more problems, 2 Python labs and 1 extra course. Everything you have used here stays free, always.