/* File: FibIt.java - March 2011 */ package l04; /** * Compute and display the Fibonacci number of the input argument * using an iterative algorithm. Long values are returned so that * quite large inputs (e.g. 100) are possible. * * Sample usage: java l04.FibIt 5 * * @author Michael Albert * */ public class FibIt{ 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) { // a and b will track a successive pair of Fibonacci numbers // The bounds on the for loop mean that at the end, b will be // the one we want long a = 1, b = 1; for(int i = 1; i < n; i++) { // We want the current b to become the new a // and the sum of current a and current b to be the new b long c = b; b += a; a = c; } return b; } }