ernie.WPI.EDU> cat class17c.C // file class17b.C, cs2223, D97/98 // // Fibonacci sequence using lookup table // 09Apr08 NW, First version // includes #include "n_int.h" // Class 2, Problem 1, and Problem 2 #include "Timer.h" // see Class 2 // definitions #define FIB_MAX 1000 // prototype n_int fib(int); // Fibonacci sequence // main int main () { Timer *timer; timer = new Timer(1); cout << "fib(" << FIB_MAX <<") =" << endl; (fib(FIB_MAX).print(75)); // calculate and print a big fibonacci number delete timer; // print out the time cout << endl; timer = new Timer(2); for (int n = 0; n <= 1000; n++) fib(FIB_MAX); // call the function 1000 times delete timer; // print out the time return 0; } // end main() n_int fib(int n) // Fibonacci sequence { static n_int fib[FIB_MAX + 1]; // be careful, this can become BIG static int first_time = 1; static int size = -1; // the last value calculated static n_int error; if (first_time) // initialize the array { (fib[0]).make(0); (fib[1]).make(1); size = 1; error.make(0); first_time = 0; } if (n > FIB_MAX) return error; // too big if (n < 0) return error; // too small if (n > size) // calculate only what is needed, but remember it { for (int m = size+1; m <= n; m++) fib[m] = fib[m-1] + fib[m-2]; size = n; } return fib[n]; } // end fib() // Copyright 1998 Norman Wittels ernie.WPI.EDU> g++ class17c.C Timer.C n_int.C ernie.WPI.EDU> a.out fib(1000) = 434665576869374564356885276750406258025646605173717804024817290895365554179 490518904038798400792551692959225930803226347752096896232398733224711616429 96440906533187938298969649928516003704476137795166849228875 Process 1 took 1.09996 seconds Process 2 took 0.099996 seconds ernie.WPI.EDU>