斐波那契数列

 1 /*
 2 * 斐波那契数0,1,1,2,3,5,8,13
 3 * 求第N个斐波那契数(从第0项开始)
 4 * */
 5 public class Test {
 6     /*这种方法到了N为几十的时候,运算会非常慢
 7      例如N=5,调4和3,4调3和2,3调2和1,有很多重复调用,因此速度非常慢
 8      调用次数是1+2+4+8+……,2^0+2^1+2^2+2^3+……=2^n -1=0.5*2^n -1,最后O(2^n)
 9      */
10    public static  int fbnq(int n)
11    {
12        if (n<=1)
13            return n;
14        return  fbnq(n-1)+fbnq(n-2);
15    }
16     public  static  int fbnq2(int n)
17     {
18         if(n<=1)
19             return  n;
20         int first=0;
21         int second=1;
22         //输入第N项时,加了N-1次
23         for( int i=0;i<n-1;i++)
24         {    //第二个数变为了第一个数,相加的和变为第二个数
25             int sum=first+second;
26             first=second;
27             second=sum;
28         }
29        return  second;
30     }
31     public static void main(String[] args) {
32         System.out.println(fbnq(0));
33         System.out.println(fbnq(1));
34         System.out.println(fbnq(5));
35         System.out.println(fbnq2(64));
36     }
37 }
原文地址:https://www.cnblogs.com/kc1995/p/13862015.html