微软算法面试(14):用最快的方法计算出 Fibonacci数列中的第n项

使用通项公式的方式,算法复杂度为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

 

posted @ 2021-01-30 22:38  天涯学馆  阅读(49)  评论(0编辑  收藏  举报