Algorithm

Fibonacci

2017-11-14  本文已影响8人  几千里也

先上代码

// The 93rd Fibonacci number would overflow a long, but
// this will take so long to compute with this function
// that we don't bother to check for overflow.
public class Fibonacci {
    public static long fibonacci(int n) {
        if (n < 2) {
            return n;
        } else {
            // using recursion
            // return fibonacci(n-1) + fibonacci(n-2);

            // without using recursion
            long n0 = 0, n1 = 1, n2;
            int i = 1;
            do {
                n2 = n0 + n1;
                n0 = n1;
                n1 = n2;
                ++i;
            } while (i < n); 

            return n2;
        }
    }

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

编译运行

# javac Fibonacci.java
# java Fibonacci 8
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
Fibonacci
上一篇下一篇

猜你喜欢

热点阅读