/** * Test of a simple Fibonacci number calculator.
* * @author Wayne Eberly */ public class Fibonacci1 { /** * Test of a simple Fibonacci number calculator. */ public static void main(String[] args) { System.out.println("Test of a Simple Fibonacci Number Calculator"); System.out.println(""); for (int i=0; i <= 40; i++){ System.out.print("n: "); System.out.printf("%2d", i); System.out.print("; nth Fibonacci number: "); System.out.printf("%10d", fib(i)); System.out.println(""); } } /** * Computes a specified Fibonacci number as a long integer by a direct * application of the recursive definition. * *

* Precondition: * i is a nonnegative integer.
* Postcondition: * Value returned is the ith * Fibonacci number. *

* * @param i Index of the Fibonacci number to be calculated * @return The ith Fibonacci number * @throws IllegalArgumentException If the input integer is negative * */ public static long fib(int i) { 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 return fib(i-1) + fib(i-2); } } } } }