这题可以参考Zyearn的博客(斐波那契数列的几种计算机解法):
http://blog.csdn.net/zyearn/article/details/7878657
使用通项公式的方式,算法复杂度为o(1),应该是最快的。
先看下Fibonacci数列的定义:
使用通项公式的概念,可以得到:
使用矩阵计算可以得到:
计算详细过程,请参考:http://blog.csdn.net/zyearn/article/details/7878657
实现过程如下:
#include<iostream>
#include<math.h>
using namespace std;
int fi(int n)
{
if(n < 0) return -1;
int res = 1.0/sqrt(5)*(pow((1.0+sqrt(5))/2, n) -pow((1.0-sqrt(5))/2, n));
return res;
}
int main()
{
cout << "fi(5)= " << fi(5) << endl;
return 0;
}
实现如下:
fi(5)=5