Fibonacci --矩阵快速幂

菲波那契数列是指这样的数列: 数列的第一个是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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值