菲波那契数列是指这样的数列: 数列的第一个是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
ac代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int mod=10000;
struct node{
int p[110][110];
};
int n=2;
node q(node a,node b)
{
node ans;
memset(ans.p,0,sizeof(ans.p));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
for(int k=1;k<=n;k++){
ans.p[i][j]=(ans.p[i][j]+a.p[i][k]*b.p[k][j]%mod)%mod;
}
}
}
return ans;
}
node p(node a,int nn)
{
node res;
memset(res.p,0,sizeof(res.p));
for(int i=1;i<=n;i++)res.p[i][i]=1;
while(nn){
if(nn&1)res=q(res,a);
nn>>=1;
a=q(a,a);
}
return res;
}
int main()
{
int N;
while(cin>>N){
if(N==-1)break;
if(N==0){
printf("0\n");
continue;
}
if(N==1||N==2){
printf("1\n");
}
else{
node a,b;
a.p[1][1]=1;a.p[1][2]=0;
a.p[2][1]=1;a.p[2][2]=0;
b.p[1][1]=1;b.p[1][2]=1;
b.p[2][1]=1;b.p[2][2]=0;
node ans=p(b,N-2);
ans=q(ans,a);
printf("%d\n",ans.p[1][1]);
}
}
return 0;
}