poj 3070 Fibonacci

/*            
矩阵乘法
1 1
题意:有一矩阵 A= 1 0 , 令B=A^n, 输出 B[0][1]的后四位数字
*/


#include <iostream> //矩阵乘法, 由于矩阵乘法具有结合律,所以计算A^n可以使用二分快速求幂
using namespace std;

struct node
{
int g[2][2];
};
int m=10000;
node multiply(node a,node b) //2*2矩阵相乘
{

node res;
res.g[0][0]=(a.g[0][0]*b.g[0][0]+a.g[0][1]*b.g[1][0])%m;
res.g[0][1]=(a.g[0][0]*b.g[0][1]+a.g[0][1]*b.g[1][1])%m;
res.g[1][0]=(a.g[1][0]*b.g[0][0]+a.g[1][1]*b.g[1][0])%m;
res.g[1][1]=(a.g[1][0]*b.g[0][1]+a.g[1][1]*b.g[1][1])%m;
return res;
}
node pow(node p,int k) //二分法计算矩阵p的k次方
{

if(k==1)
return p;
else
{
node q=pow(p,k/2);
if(k%2==0)
return multiply(q,q);
else
return multiply( multiply(q,q) , p );
}
}
int main()
{
int n;
while(cin>>n&&n!=-1)
{
if(n==0)
{
cout<<"0\n";
continue;
}
node A;
A.g[0][0]=A.g[0][1]=A.g[1][0]=1;
A.g[1][1]=0;
A=pow(A,n);
cout<<A.g[0][1]<<endl;
}
return 0;
}

posted on 2011-07-22 15:08  sysu_mjc  阅读(129)  评论(0编辑  收藏  举报

导航