Number Sequence (斐波那契的矩阵快速幂)

就是一个模板而已。 为了保存一下代码~


#include<iostream>
#include<vector>
#include<cmath>
#include<map>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<queue>
#include<cmath>
#include<set>
#include<string>
#define INF 1000000005
#define LL long long
using namespace std;
const int MAXN =5;
struct Matrix
{
    int n,m;
    int a[MAXN][MAXN];
    void clear(int x=0,int y=0)
    {
        n=x;
        m=y;
        memset(a,0,sizeof(a));
    }
    Matrix operator * (const Matrix &b)const
    {
        Matrix tmp;
        tmp.clear(n,b.m);
        for(int i=0; i<n; ++i)
            for(int j=0; j<b.m; ++j)
                for(int k=0; k<m; ++k)
                {
                    tmp.a[i][j]+=a[i][k]*b.a[k][j];
                    tmp.a[i][j]%=7;
                }
        return tmp;
    }
    void show()
    {
        for(int i=0; i<n; ++i)
        {
            for(int j=0; j<m; ++j)
                cout<<a[i][j]<<" ";
            cout<<endl;
        }
    }
};
Matrix quickPow(Matrix mat,int n)
{
    Matrix res;
    res.clear(2,2);
    res.a[0][0]=res.a[1][1]=1;
    while(n)
    {
        if(n&1) res=res*mat;
        mat=mat*mat;
        n=n>>1;
    }
    return res;
}
int main()
{
    int A,B,n;
    while(scanf("%d%d%d",&A,&B,&n)!=EOF)
    {
        if(!A&&!B&&!n) break;
        if(n==1||n==2)
        {
            puts("1");
            continue;
        }
        Matrix mat;
        mat.clear(2,2);
        mat.a[0][0]=0;
        mat.a[0][1]=B;
        mat.a[1][0]=1;
        mat.a[1][1]=A;
        Matrix f;
        f.clear(1,2);
        f.a[0][0]=1;
        f.a[0][1]=1;
        n-=2;
        Matrix s=f*quickPow(mat,n);
        printf("%d\n",(s.a[0][1])%7);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值