HDU 1005 Number Sequence 矩阵快速幂

矩阵快速幂算法解析
本文介绍了一种利用矩阵快速幂解决特定类型问题的方法。通过定义矩阵运算和快速幂函数,可以高效地计算出一系列数学问题的答案。适用于求解斐波那契数列等递推问题。

主要是构造矩阵
a , b
1 , 0
最后是m[0][0]+m[0][1]
模板题

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
const LL mod = 7;
int A, B, n;
struct matrix{
    LL m[2][2];
};
matrix operator * (const matrix a,const matrix b)
{
    matrix ans;
    for(int i=0;i<2;++i)
    {
        for(int j=0;j<2;++j)
        {
            ans.m[i][j]=0;
            for(int k=0;k<2;++k)
            {
                ans.m[i][j] = (ans.m[i][j]+a.m[i][k]*b.m[k][j])%mod;
            }
            ans.m[i][j]%=mod;
        }
    }
    return ans;
}
LL quick_pow(int a, int b)
{
    matrix ans, res;
    ans.m[0][0]=a, ans.m[0][1]=b;
    ans.m[1][0]=1, ans.m[1][1]=0;
    res.m[0][0]=1, res.m[0][1]=0;
    res.m[1][0]=0, res.m[1][1]=1;
    if(n==1||n==2)
        return 1;
    n=n-2;
    while(n)
    {
        if(n&1)
            res=ans*res;
        n>>=1;
        ans=ans*ans;
    }
    return (res.m[0][0]+res.m[0][1])%mod;
}
int main()
{
    while(scanf("%d %d %d", &A, &B, &n), n&&A&&B)
    {
        printf("%lld\n", quick_pow(A, B));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值