/* File: FibArray.java - March 2011 */ package l04; /** * Compute and display the Fibonacci number of the input argument * using an iterative algorithm, and storing intermediate results * in an array. This mimics how the computations would be * done 'on paper'. Its only disadvantage is that the storage use * in the fib method is not actually needed as the other implementations * demonstrate. Long values are returned so that quite large inputs * (e.g. 100) are possible. * * Sample usage: java l04.FibArray 5 * * @author Michael Albert * */ public class FibArray{ public static void main(String[] args) { int n = Integer.parseInt(args[0]); System.out.println("Fib(" + n + ") = " + fib(n)); } public static long fib(int n) { if (n <= 1) return 1; long[] fib = new long[n+1]; fib[0] = 1; fib[1] = 1; for(int i = 2; i <= n; i++) { fib[i] = fib[i-1] + fib[i-2]; } return fib[n]; } }