#include<iostream>

#include<cmath>

using namespace std;

//方法一：递归调用,有大量重复计算，效率低

long long Fibonacci1(int n)

{

return (n < 2) ? n : Fibonacci1(n - 1) + Fibonacci1(n - 2);

}

//方法二：非递归数组方式,循环中仍然有重复计算

long long Fibonacci2(int n)

{

long long *fibArray = new long long[n + 1];

fibArray[0] = 0;

fibArray[1] = 1;

for (int i = 2; i <= n; i++)

{

fibArray[i] = fibArray[i - 1] + fibArray[i - 2];

}

long long ret = fibArray[n];

delete[] fibArray;

return ret;

}

//方法三：非递归循环方式，将前两项的计算结果保存起来，无重复计算

long long Fibonacci3(int n)

{

long long fibArray[3] = { 0, 1, n };//给fibArray数组赋初值

for (int i = 2; i <= n; i++)

{

fibArray[2] = fibArray[1] + fibArray[0];

fibArray[0] = fibArray[1];

fibArray[1] = fibArray[2];

}

return fibArray[2];

}

//方法四：直接利用数学公式法：f(n)={[(1+5^0.5)/2]^n - [(1-5^0.5)/2]^n}/(5^0.5)

long long Fibonacci4(int n)

{

return (pow((1 + sqrt(5.0)) / 2, n) - pow((1 - sqrt(5.0)) / 2, n)) / sqrt(5.0);

}

//测试代码

int main()

{

int num = 0;

int ret = 0;

cout << "请输入斐波拉契数列的序号:";

cin >> num;

ret = Fibonacci1(num);

/*ret = Fibonacci2(num);*/

/*ret = Fibonacci3(num);*/

/*ret = Fibonacci4(num);*/

cout << ret << endl;

system("pause");

return 0;

}

f(n)      f(n-1)        1    1

[                 ] = [          ]^(n-1)

f(n-1)    f(n-2)        1    0