时间复杂度为O(log(n))
// 程序员面试100题之16斐波那契数列.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct Matrix2by2{
int value00,value01,value10,value11;
Matrix2by2(int v00,int v01,int v10,int v11):value00(v00),value01(v01),value10(v10),value11(v11)
{}
Matrix2by2()
{}
};
Matrix2by2 MatrixMultiply(Matrix2by2 M1,Matrix2by2 M2)
{
Matrix2by2 M;
M.value00= M1.value00*M2.value00+M1.value01*M2.value10;
M.value01= M1.value00*M2.value01+M1.value01*M2.value11;
M.value10= M1.value10*M2.value00+M1.value11*M2.value10;
M.value11= M1.value10*M2.value01+M1.value11*M2.value11;
return M;
}
Matrix2by2 MatrixAdd(Matrix2by2 M1,Matrix2by2 M2)
{
Matrix2by2 M;
M.value00= M1.value00+M2.value00;
M.value01= M1.value01+M2.value01;
M.value10= M1.value10+M2.value10;
M.value11= M1.value11+M2.value11;
return M;
}
void print (Matrix2by2 M)
{
cout<<endl;
cout<<M.value00<<" "<<M.value01<<endl;
cout<<M.value10<<" "<<M.value11<<endl;
}
Matrix2by2 MatrixPow(Matrix2by2 M,int n)
{
Matrix2by2 result(1,0,0,1);
Matrix2by2 temp=M;
for(;n;n=n>>1)
{
if(n&1)result =MatrixMultiply(result,temp);// notice && is not &
temp=MatrixMultiply(temp,temp);
}
return result;
}
int Finonacci(int n)
{
if(n==0)return 0;
if(n==1)return 1;
Matrix2by2 E(1,1,1,0),M;
M=MatrixPow(E,n-1);
print(M);
return M.value00;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cin>>n;
cout<<Finonacci(n);
system("pause");
return 0;
}