INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Fibonacci.java.

/*************************************************************************
 *  Compilation:  javac Fibonacci.java
 *  Execution:    java Fibonacci N
 *  
 *  Computes and prints the first N Fibonacci numbers using the
 *  following recurrence:
 *
 *         f(1) = f(2) = 1
 *         f(n) = f((n+1)/2)^2 + f((n-1)/2)^2   if n is odd
 *         f(n) = f(n/2 + 1)^2 - f(n/2 - 1)^2   if n is even
 *
 *   % java Fibonacci 7
 *   1
 *   1
 *   2
 *   3
 *   5
 *   8
 *   13
 *
 *************************************************************************/

public class Fibonacci {
    static long fib(int n) {

        // base case
        if (n == 1 || n == 2) return 1;

        // n is odd
        if (n % 2 == 1) {
            long a = fib((n+1)/2);
            long b = fib((n-1)/2);
            return a*a + b*b;
        }

        // n is even
        long a = fib(n/2 + 1);
        long b = fib(n/2 - 1);
        return a*a - b*b;
    }

    public static void main(String[] args) {
        long N = Long.parseLong(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(fib(i));
    }

}




Last updated: Wed Feb 11 18:10:39 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.