Fibonacci

作者: 几千里也 | 来源:发表于2017-11-14 10:49 被阅读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

    相关文章

      网友评论

        本文标题:Fibonacci

        本文链接:https://www.haomeiwen.com/subject/eiuxvxtx.html