Search This Blog

Tuesday, June 14, 2011

Print a sequence of Fibonacci number

The trick is that you should use BigInteger instead of long.  Otherwise, you will get overflow pretty soon.  Here is the code:

import java.math.BigInteger;

public class Fibonacci {
    /**
     * print out a list of Fibonacci sequence to n places.
     * if n = 0, no number will be printed out.  if n = 1, print the first Fibonacci number.
     *
     * @param n the number of Fibonacci to be printed out
     */
    public static void print(int n) {
        BigInteger f0 = BigInteger.ZERO;
        BigInteger f1 = BigInteger.ONE;
        for (int i = 0; i < n; i++) {
           
            System.out.print(f0);
            if (i != n - 1) {
                System.out.print(", ");
            }
            BigInteger temp = f1;
            f1 = f1.add(f0);
            f0 = temp;
        }
    }
}

Update: Another thing to consider is that don't use recursive method to compute Fibonacci number because it is too expensive.  The run time is 2^n to recursively compute Fibancci number.

No comments:

Post a Comment