class Fibonacci { /* Recursively computes the nth fibonacci number according to definition. */ static long rfib(int n) { if (n < 2) return n; return rfib(n-1) + rfib(n-2); } /////////////////////////////////////////////////////////////////////////////////// /* Computes the nth fibonacci number using bottom-up Dynamic Programming. */ static long dpfib(int n) { if (n < 2) return n; long[] table = new long[n+1]; table[0] = 0; table[1] = 1; for (int i = 2; i <= n; i++) table[i] = table[i-1] + table[i-2]; return table[n]; } /////////////////////////////////////////////////////////////////////////////////// /* Computes the nth fibonacci number using space-efficient bottom-up Dynamic Programming. */ static long dpfib_space(int n) { if (n < 2) return n; long fn_2 = 0, fn_1 = 1; for (int i = 2; i <= n; i++) { long temp = fn_1; fn_1 += fn_2; fn_2 = temp; } return fn_1; } /////////////////////////////////////////////////////////////////////////////////// // Any value that's impossible for a fibonacci number will do. static final long UNKNOWN = -1; /* Precondition: n >= 0 * Computes the nth fibonacci number using Memoization. */ static long mpfib(int n) { // Creates the table and fills it with UNKNOWN. long[] table = new long[n+1]; for (int i = 0; i <= n; i++) table[i] = UNKNOWN; // Computes f(n) using the recurrence & the table. return memoize(n, table); } /* Precondition: n >= 0 */ static long memoize(int n, long[] table) { if (table[n] == UNKNOWN) { if (n < 2) { table[n] = n; } else { table[n] = memoize(n-1, table) + memoize(n-2, table); } } return table[n]; } public static void main(String[] args) { for (int n = 0; n < 10; n++) { System.out.printf("rfib(%d) = %d, ", n, rfib(n)); System.out.printf("dpfib(%d) = %d, ", n, dpfib(n)); System.out.printf("dpfib_space(%d) = %d%n", n, dpfib_space(n)); System.out.printf("mpfib(%d) = %d%n", n, mpfib(n)); } int n = 40; Stopwatch watch = new Stopwatch(); /* System.out.printf("rfib(%d) = %d%n", n, rfib(n)); double t1 = watch.elapsedTime(); System.out.printf("time for rfib(%d) is %f%n", n, t1); System.out.printf("mpfib(%d) = %d%n", n, mpfib(n)); double t1 = watch.elapsedTime(); System.out.printf("time for mpfib(%d) is %f%n", n, t1); System.out.printf("dpfib(%d) = %d%n", n, dpfib(n)); double t2 = watch.elapsedTime(); System.out.printf("time for dpfib(%d) is %f%n", n, t2-t1); */ } }