Fibonacci POJ - 3070(矩阵快速幂递推)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值