INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of SlowFibonacci.java.

/*************************************************************************
 *  Compilation:  javac SlowFibonacci.java
 *  Execution:    java SlowFibonacci N
 *  
 *  Computes and prints the first N Fibonacci numbers.
 *  Warning:  this program is spectacularly inefficient and is meant
 *            to illustrate a performance bug, e.g., set N = 45.
 *
 *
 *   % java SlowFibonacci 7
 *   1: 1
 *   2: 1
 *   3: 2
 *   4: 3
 *   5: 5
 *   6: 8
 *   7: 13
 *
 *************************************************************************/

public class SlowFibonacci {
    static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }

}




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