package Fibonacci2; /** * Fibonacci Number Calculator. * * @author Wayne Eberly */ public class Fibonacci { public static long fib(int i) throws NumericalOverflowException { if (i<0) { throw new IllegalArgumentException("Negative Input: " + i); } else { // i >= 0 if (i==0) { return 0; } else { // i >= 1 if (i==1) { return 1; } else { // i >= 2 if (i >= 92) { // Too large for input to // represent the output throw new NumericalOverflowException("Overflow when computing the " + i + "th Fibonacci number"); } else { // Output can be represented long previous = 0; long current = 1; long next; for (int j=1; j < i; j++) { /* * Loop Invariant: * a) j is an integer such that 1 <= j <= i-1 * b) previous is equal to the j-1'st Fibonacci * number * c) current is equal to the j'th Fibonacci number * Loop Variant: i-j */ next = previous + current; previous = current; current = next; assert (previous == SFibonacci.fib(j)) && (current == SFibonacci.fib(j+1)); }; return current; } } } } } }