package rebelsky.exam2; import java.math.BigInteger; /** * Oh boy! Fun with Fibonacci numbers. * * @author Samuel A. Rebelsky * @version 1.0 of October 2004 */ public class Fib { /** * A count of the number of calls made. */ int calls; /** * An array to store the partially computed values. */ BigInteger[] computed; /** * Compute the nth Fibonacci number (inefficiently). */ public BigInteger badfib(int n) { ++this.calls; if (n < 2) return BigInteger.valueOf(n); else return badfib(n-1).add(badfib(n-2)); } // badfib /** * Compute the nth Fibonacci number (efficiently) */ public BigInteger fib(int n) { // Make sure the array exists and is suffiently big if ((computed == null) || (computed.length <= n)) { computed = new BigInteger[n+1]; computed[0] = BigInteger.valueOf(0); computed[1] = BigInteger.valueOf(1); } // See if the value is already there if (computed[n] == null) { computed[n] = fib(n-1).add(fib(n-2)); } return computed[n]; } // fib(int) /** * Reset the number of calls made. */ void resetCalls() { this.calls = 0; } // resetCalls() /** * Get the number of calls made. */ int getCalls() { return this.calls; } // getCalls() } // class Fib