public class Fibonacci4 { // Same counter as before. static int numCalls; // We'll use an array to record previously computed values: static int[] fValues; public static void main (String[] argv) { // Test case 1: int n = 5; // Initialize both the counter and the array: numCalls = 0; fValues = new int [n+1]; int f = fibonacci (n); System.out.println ("f(" + n + ") = " + f + " numCalls=" + numCalls); // Test case 2: n = 20; // Initialize both the counter and the array: numCalls = 0; fValues = new int [n+1]; f = fibonacci (n); System.out.println ("f(" + n + ") = " + f + " numCalls=" + numCalls); } static int fibonacci (int n) { // We are recording the number of times this method is called. numCalls ++; if (n <= 2) { // First time we reach here, we store the values. fValues[n] = n-1; return (n-1); } // If the values haven't been computed, then compute and store. if (fValues[n-1] == 0) { fValues[n-1] = fibonacci(n-1); } if (fValues[n-2] == 0) { fValues[n-2] = fibonacci(n-2); } // By the time we reach here, previous fib values have been stored. fValues[n] = fValues[n-1] + fValues[n-2]; return fValues[n]; } }