CS106X
Handout 20
Autumn 2010
October 11
th
, 2010
Memoization
Let’s review why our first recursive implementation of
Fibonacci
was so dreadfully slow.
Here’s the code again, updated to make use of the
long
long
data type so that much,
much larger Fibonacci numbers can, in theory and given an infinite amount of time, be
computed:
unsigned long long Fibonacci(int n) {
if (n < 2) return n;
return Fibonacci(n  1) + Fibonacci(n  2);
}
The code mirrors the inductive definition as closely as one could possibly imagine, but
because each call to Fibonacci, in general, gives birth to two more, the running time grows
exponentially with respect to
n
.
One key observation: the initial recursive call leads to many (many, many) repeated
recursive calls.
The computation of the 40
th
Fibonacci number, for instance, leads to:
o
1 call to
Fibonacci(39)
o
2 calls to
Fibonacci(38)
o
3 calls to
Finbonacci(37)
o
5 calls to
Fibonacci(36)
o
8 calls to
Fibonacci(35)
o
13 calls to
Fibonacci(34)
o
21 calls to
Fibonacci(33)
….
It’s sad that
Fibonacci(33)
gets calls 21 different times, because it needs to build up the
answer from scratch every single time, even though the answer is always the same.
The
overall implementation of Fibonacci is farcically slow because it spends a laughably large
fraction of its time recomputing the same results over and over again.
One very common, simple, and clever technique to overcome the repeated subproblem
issue is to keep track of all previously computed results in a
Map
, and to always consult the
Map
to see if something’s already been computed before committing to the time
consuming recursion.
The code that appears below is an extension of the above, save for the key addition that a
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '08
 Cain,G
 DNA, Recursion, Long integer, Fibonacci number, Golden ratio

Click to edit the document details