HDU 4549

QQ截图20150901181925

水题: 费马小定理+快速幂+矩阵快速幂

(第一次用到费马小定理)

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD  = 1000000006;
const LL MOD1 = 1000000007;
struct Matrix
{
    LL NUM[2][2];
    Matrix operator + (const Matrix a) const
    {
        Matrix c;
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
            {
                c.NUM[i][j] = NUM[i][j] + a.NUM[i][j];
            }
        }
        return c;
    }
    Matrix operator * (const Matrix a) const
    {
        Matrix c;
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
            {
                c.NUM[i][j] = 0;
                for(int k = 0; k < 2; ++k)
                    c.NUM[i][j] = (c.NUM[i][j] + NUM[i][k] * a.NUM[k][j] % MOD) % MOD;
            }
        }
        return c;
    }
};

Matrix ppow(Matrix a, LL n)
{
    Matrix ret;
    for(int i =0 ; i< 2; ++i)
    {
        for(int j = 0; j < 2; ++j)
            ret.NUM[i][j] = i==j ? 1 : 0;
    }
    while(n)
    {
        if(n & 1) ret = ret * a;
        a = a * a;
        n >>= 1;
    }
    return ret;
}

LL Pow(LL a, LL n)
{
    LL ret = 1;
    while(n)
    {
        if(n & 1) ret =ret * a % MOD1;
        a = a * a % MOD1;
        n >>= 1;
    }
    return ret;
}

int main()
{
    LL a, b, n;
    Matrix E;
    E.NUM[0][0] = 1; E.NUM[0][1] = 1;
    E.NUM[1][0] = 1; E.NUM[1][1] = 0;
    while(cin >> a >> b >> n)
    {
        if(n == 0) cout << a << endl;
        else if(n == 1) cout << b << endl;
        else
        {
            n -= 1;
            Matrix tmp = ppow(E,n);
            LL na = tmp.NUM[0][1] , nb = tmp.NUM[0][0];
            LL ans = (Pow(a,na) * Pow(b,nb))%MOD1;
            cout << ans << endl;
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/aoxuets/p/4776518.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值