做完上一个题之后顿时觉得这个题水到家了~~
--为什么不先做这个题呢?
--我不知道啊~~
题目大意:
给出Fibonacci的第n项的矩阵递推方法,问Fn的最后四位是什么。
解题思路:
矩阵快速幂取模。
下面是代码:
#include <set>
#include <map>
#include <queue>
#include <math.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define eps 1e-7
#define pi acos(-1.0)
#define inf 107374182
#define inf64 1152921504606846976
#define lc l,m,tr<<1
#define rc m + 1,r,tr<<1|1
#define iabs(x) ((x) > 0 ? (x) : -(x))
#define clear1(A, X, SIZE) memset(A, X, sizeof(A[0]) * (SIZE))
#define clearall(A, X) memset(A, X, sizeof(A))
#define memcopy1(A , X, SIZE) memcpy(A , X ,sizeof(X[0])*(SIZE))
#define memcopyall(A, X) memcpy(A , X ,sizeof(X))
#define max( x, y ) ( ((x) > (y)) ? (x) : (y) )
#define min( x, y ) ( ((x) < (y)) ? (x) : (y) )
using namespace std;
struct node
{
long long matrix[2][2];
} a,temp;
int n,m,d,k;
node does(node a,node b)
{
node c;
clearall(c.matrix,0);
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
for(int k=0; k<2; k++)
c.matrix[i][j]+=a.matrix[i][k]*b.matrix[k][j];
c.matrix[i][j]%=10000;
}
}
return c;
}
void mul(int k)
{
temp.matrix[0][0]=1;
temp.matrix[1][1]=1;
temp.matrix[0][1]=0;
temp.matrix[1][0]=0;
while(k)
{
if(k&1)temp=does(temp,a);
a=does(a,a);
k>>=1;
}
}
int main()
{
while(scanf("%d",&k),k!=-1)
{
if(k==0)
{
puts("0");
continue;
}
a.matrix[0][0]=1;
a.matrix[1][1]=0;
a.matrix[0][1]=1;
a.matrix[1][0]=1;
mul(k);
printf("%d\n",temp.matrix[1][0]);
}
return 0;
}