Fibonacci数列的两种算法

          一种是递归算法,临时输入n,递归计算出f(n);一种是先计算一遍,将结果储存起来,在用循环找出来。下面用C++将两种算法演示一遍。

  1 /*First */

  2 #include<iostream>

  3 using namespace std;

  4 int main()

  5 {

  6     int Fib1(int n);

  7     cout<<"please enter the number you want to caculate :"<<endl;

  8     int n;

  9     cin>>n;

 10     cout<<Fib1(n-1)<<endl;                     //注:第一个数是从序号0开始计数的,计算机都是这样,所                                                                        //以遵从计算机

 11     return 0;

 12 }

 13 int Fib1(int n)                          //First kind of Fibonacci

 14 {

 15     if(0==n)

 16     {

 17         return 0;

 18     }

 19     if(1==n)

 20     {

 21         return 1;

 22     }

 23     else

 24     {

 25         return Fib1(n-1)+Fib1(n-2);

 26     }

 27 }

下面是第二种算法:
  1 /* Second */
  2 #include<iostream>
  3 using namespace std;
  4 int main()
  5 {
  6     int iTmp,n;
  7     cout<<"Enter how many number do you want to caculate :"<<endl;
  8     cin>>n;
  9     int *a=new int [n];
 10     a[0]=0;
 11     a[1]=1;
 12     for(int i=2;i<n;++i)
 13     {
 14         iTmp=a[1];
 15         a[i]=a[i-1]+a[i-2];
 16     }
 17     cout<<"你想查第几个数 ?"<<endl;
 18     cin>>n;
 19     cout<<"结果是:"<<a[n-1]<<endl;
 20     return 0;
 21 }
这两种算法的不同之处在于在大型计算时第一种所花费时间比较多,由于现在比较忙,原因请读者自己分析。以后有时间会慢慢码字把原因贴出来。(第一次写博客,有错误请指出来,谢谢 (~_~))