Fast Fibonacci

Chapter: Instrumenting Programs
...Section: Fast Fibonacci

The key to speeding up the fibonacci program is memoization. We will keep an array done filled with previously computed fibonacci numbers. Here's simple code:

public class FastFib {
    static int[] done = new int[1000];
    public static int f(int n) {
	if (n <= 1) return 1;
	if (done[n] == 0) done[n] = (f(n-1) + f(n-2));
	return done[n];
    }
    public static void main(String[] args) {
	int n = new Integer(args[0]);
	System.out.println("The " + n + "th fibonacci is " + f(n));
    }
}

The array done keeps track of what's already been computed. When we try to compute, for example, f(21) we first check to see if done[21] is anything but 0. If it is, that means we've already computed f(21) wo we'll simply return the previously computed result stored in done[21]. Otherwise we'll compute the value f(n-1) + f(n-2) and store the result in done[21] before returning it. The process is called memoization and it's one technique for transforming a slow program into an equivalent faster program. Our textbook explains dynamic programming. It works similarly by reordering the execution steps so that an array of fibonacci numbers is gradually built up.


Exercise 6

Add instrumentation to FastFib to show how many calls are made to f(10). Comment. See how fast java FastFib 40 runs now!

Deliverable Code in your zipped submission, your observations in your lab notebook.


In fact, FastFib is so fast we're tempted to try it with inputs like 41, 42, 43, 44, 45, 46, ... It's lightning fast compared to the old Fib, but what's with the value of java FastFib 46?

Q. 1
What's up?


What's needed is a different class of numbers that's not limited by the size of registers. Look at the program BigFastFib.java. It uses the class BigInteger so we can handle really big numbers. You can do fib(5000) pretty quickly.


Exercise 7

Instrument the BigFastFib program to count how many time f(10) is called. Comment. Write up your conclusions.

Deliverables Instrumented code, your conclusions in your lab notebook.



rhyspj@gwu.edu