首页 > 其他 > 详细

矩阵快速幂

时间:2019-10-06 16:49:13      阅读:62      评论:0      收藏:0      [点我收藏+]

在斐波那契数列中,Fib0=0,Fib1=1,Fibn=Fibn1+Fibn2(n>1)Fib0=0,Fib1=1,Fibn=Fibn−1+Fibn−2(n>1)。

给定整数n,求Fibnmod10000Fibnmod10000。

输入格式

输入包含多组测试用例。

每个测试用例占一行,包含一个整数n。

当输入用例n=-1时,表示输入终止,且该用例无需处理。

输出格式

每个测试用例输出一个整数表示结果。

每个结果占一行。

数据范围

0n21090≤n≤2∗109

输入样例:

0
9
999999999
1000000000
-1

输出样例:

0
34
626
6875







 

 


代码;
技术分享图片
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
const int mod  = 10000;
int mul(int f[2],int a[2][2])
{
    int c[2];
    memset(c,0,sizeof(c));
    for(int j=0;j<2;j++)
    {
        for(int k=0;k<2;k++)
        c[j] = (c[j]+(ll) f[k]*a[k][j])%mod;
    }
    memcpy(f,c,sizeof(c));
}
int mulself(int a[2][2])
{
    int c[2][2];
    memset(c,0,sizeof(c));
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            for(int k=0;k<2;k++)
            {
                c[i][j] = (c[i][j] + (ll)a[i][k]*a[k][j])%mod;
            }
        }
    }
    memcpy(a,c,sizeof(c));
}
int main()
{
    int n;
    while(~scanf("%d",&n)&&n!=-1)
    {
        int f[2]={0,1};
        int a[2][2] ={{0,1},{1,1}};
        for(;n;n>>=1)
        {
            if(n&1)mul(f,a);
            mulself(a);
        }
        cout << f[0] << endl;
    }
    return 0;
}
View Code

 

矩阵快速幂

原文:https://www.cnblogs.com/wangzhe52xia/p/11627510.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!