菲波那契数列是指这样的数列: 数列的第一个是0和第二个数是1,接下来每个数都等于前面2个数之和。 给出一个正整数a,要求菲波那契数列中第a个数的后四位是多少。
Input
多组数据 -1结束 范围1~10^9
Output
第x项的后4位
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
根据斐波那契的递推式构造出矩阵然后套模板:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int mod=1e4;
struct node
{
ll ma[5][5];
};
int n;
node mul(node a,node b)
{
node ans;
memset(ans.ma,0,sizeof ans.ma);
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++)
for(int k=1;k<=2;k++)
ans.ma[i][j]=(ans.ma[i][j]+a.ma[i][k]*b.ma[k][j])%mod;
return ans;
}
node pow(node a,int b)
{
node ans;
memset(ans.ma,0,sizeof ans.ma);
for(int i=1;i<=2;i++) ans.ma[i][i]=1;
while(b)
{
if(b&1) ans=mul(ans,a);
a=mul(a,a);
b>>=1;
}
return ans;
}
int main()
{
int n;
while(cin >>n)
{
if(n==-1) break;
node a,ans,b;
a.ma[1][1]=1,a.ma[1][2]=1;
a.ma[2][1]=1,a.ma[2][2]=0;
ans=pow(a,n);
cout <<ans.ma[2][1]<<endl;
}
return 0;
}