public class Fibonacci { /* Computes the nth Fibonacci number using its definition */ static long recFib(int n) { return (n < 2) ? n : recFib(n-1) + recFib(n-2); } ///////////////////////////////////////////////////////////////////////////// static long[] dpTable; /* Computes the nth Fibonacci number using bottom-up dynamic programming. */ static long dpFib(int n) { dpTable[0] = 0; if (n > 0) dpTable[1] = 1; for (int i = 2; i <= n; i++) dpTable[i] = dpTable[i-1] + dpTable[i-2]; return dpTable[n]; } /* Computes the nth Fibonacci number using bottom-up dynamic programming, * space-saving. */ static long dpSpaceFib(int n) { if (n < 2) return n; long prev = 0; long curr = 1; for (int i = 2; i <= n; i++) { curr = curr + prev; prev = curr - prev; } return curr; } ///////////////////////////////////////////////////////////////////////////// static long[] mzTable; static final long UNKNOWN = -1; static long memoize(int n) { if (mzTable[n] == UNKNOWN) mzTable[n] = (n < 2) ? n : memoize(n-1) + memoize(n-2); return mzTable[n]; } /* Computes the nth Fibonacci number using memoization (a top-down approach). */ static long mzFib(int n) { /* initialize mzTable */ for (int i = 0; i < mzTable.length; i++) mzTable[i] = UNKNOWN; return memoize(n); } ///////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { int n = Integer.parseInt(args[0]); if (n < 0) { System.err.println("argument must be a nonnegative integer"); System.exit(1); } long value; double time; Stopwatch sw1 = new Stopwatch(); value = recFib(n); time = sw1.elapsedTime(); System.out.printf("%nrecFib(%d) = %d%n", n, value); System.out.printf("time spent: %.2f%n", time); mzTable = new long[n+1]; Stopwatch sw2 = new Stopwatch(); value = mzFib(n); time = sw2.elapsedTime(); System.out.printf("%nmzFib(%d) = %d%n", n, value); System.out.printf("time spent: %.2f%n", time); dpTable = new long[n+1]; Stopwatch sw3 = new Stopwatch(); value = dpFib(n); time = sw3.elapsedTime(); System.out.printf("%ndpFib(%d) = %d%n", n, value); System.out.printf("time spent: %.2f%n", time); Stopwatch sw4 = new Stopwatch(); value = dpSpaceFib(n); time = sw4.elapsedTime(); System.out.printf("%ndpSpaceFib(%d) = %d%n", n, value); System.out.printf("time spent: %.2f%n%n", time); } }