程序员面试题100题第16题——O(logN)求Fibonacci数列

题目:定义Fibonacci数列

f(1)=0;

f(2)=1;

...

f(n)=f(n-1)+f(n-2);

输入n,用最快的方法求该数列的第n项;

分析:略

代码:

struct Matri2By2//定义2*2矩阵
{
    Matri2By2(unsigned long m00,
        unsigned long m01,
        unsigned long m10,
        unsigned long m11):m_00(m00),m_01(m01),m_10(m10),m_11(m11)
    {};//结构体的构造函数
    unsigned long m_00;
    unsigned long m_01;
    unsigned long m_10;
    unsigned long m_11;
};
Matri2By2 MatriMultiply(const Matri2By2& A,const Matri2By2& B);//矩阵相乘
Matri2By2 MatriPower(int n);//(1,1,1,0)矩阵的n次幂
void printMatri2By2(const Matri2By2& A);//打印矩阵
long long Fibonacci(unsigned int n);//求Fibonacci数列

Matri2By2 MatriMultiply(const Matri2By2& A,const Matri2By2& B)
{
    return Matri2By2(A.m_00*B.m_00+A.m_01*B.m_10,
        A.m_00*B.m_01+A.m_01*B.m_11,
        A.m_10*B.m_00+A.m_11*B.m_10,
        A.m_10*B.m_01+A.m_11*B.m_11);
}
Matri2By2 MatriPower(int n)//分治
{
    assert(n>0);
    Matri2By2 matri(0,0,0,0);

    if(n==1)
        matri=Matri2By2(1,1,1,0);
    else if((n&1)==0)
    {
        matri=MatriPower(n/2);
        matri=MatriMultiply(matri,matri);
    }else{
        matri=MatriPower((n-1)/2);
        matri=MatriMultiply(matri,matri);
        matri=MatriMultiply(matri,Matri2By2(1,1,1,0));
    }
    return matri;
}
void printMatri2By2(const Matri2By2& A)
{
    cout << A.m_00 << "\t" << A.m_01 <<"\n";
    cout << A.m_10 << "\t" << A.m_11 <<"\n";
}
long long Fibonacci(unsigned int n)
{
    if(n==1)
        return 0;
    else if(n==2)
        return 1;
    else{
        Matri2By2 m=MatriPower(n-1);
        return m.m_00;
    }
}
posted @ 2012-10-02 15:15  logzh  阅读(381)  评论(0编辑  收藏  举报