CS 3343/3341 Analysis of Algorithms
Fibonacci Numbers Using Memoization

The Memoization Approach: The usual recursive function to calculate the nth Fibonacci number takes exponential time in terms of n. This is because it calculates smaller values over and over again.

If a program just saved answers to simpler problems and looked them up when needed, the calculation would be very fast. This process is called memoization and is illustrated in the program below:

  1. The function fs below calculates the the nth Fibonacci number in the normal recursive way, very inefficiently.
  2. The function f below calculates the the nth Fibonacci number using memoization. It keeps an array F, and when the program calculates the nth Fibonacci number it stores this value into F[n]. Before calculating f(n), the program first looks to see if the answer is already stored in F[n], and just returns that value if the answer is there.


The Fibonacci Program:
Output: The output shown below has been assembled from values the above program produced (and wall clock times were added):