Fibonacci快速实现(优化)

斐波那契数列的通俗解法是利用递推公式进行递归求解,我们可以更优化的去解决它。

方法一:通项公式

斐波那契数列的递推公式是f(n)=f(n-1)+f(n-2),特征方程为:x2=x+1,解该方程得(1+sqrt(5))/2,(1-sqrt(5))/2.所以f(n)=Ax1n+Bx2n,带入f(0)=0,f(1)=1得A=sqrt(5)/5,B=-sqrt(5)/5.则f(n)求出。

方法二:分治策略

可以看出斐波那契数列有如下性质:

(fn fn-1)=(fn-1 fn-2)*A,可以得出A=(1 1;1 0)

递推可得:(fn fn-1)=(fn-1 fn-2)*A=(fn-2 fn-3)*A2=…=(f1 f0)*An-1

因此问题转化为n次幂的问题,因此幂运算有这样的性质ca+b=ca*cb,而n次幂的n可以拆成二进制的加法,所以只需要lgn次遍历即可。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Matrix MatrixPow(const Matrix& base,int exponent)
{
    Matrix temp=base;
    Matrix result=Identity;
    for(;exponent;exponent>>=1)
    {
        if(exponent&0x1)
           result*=temp;
        temp*=temp;
    }
    return result;
}
 
 
int Fibonacci(int n)
{
     Matrix A={1,1,1,0};
     Matrix a=MatrixPow(A,n-1);
     return 1*a[0][0]+0*a[1][0];
}
原文地址:https://www.cnblogs.com/informatics/p/5059700.html