【费马小定理降幂+矩阵快速幂+快速幂】M斐波那契数列 HDU - 4549

Think:
1知识点:费马小定理降幂+矩阵快速幂+快速幂
(1):费马小定理降幂:
定理:若gcd(A, M) == 1,则A^x = A^(x%Eular(M))(mod M)
注:Eular(M)为M的欧拉函数值
2题意:
已知:
F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )
输入a, b, n,询问F[n] = ?
3解题方法:
(1):
F[0] = a
F[1] = b
F[2] = b*a
F[3] = b^(2)*a
F[4] = b^(3)*a^(2)
F[5] = b^(5)*a^(3)
.
.
.
F[n] = b^(fib(n-1))*a^(fib(n-2))
(2):由于快速幂指数太高,因此需要通过费马小定理降幂

vjudge题目链接

以下为Accepted代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int mod = 1000000007;

struct Matrix{
    LL v[4][4];
};

Matrix multiply(const Matrix &a, const Matrix &b, int Matrix_len);
Matrix matrix_pow(Matrix &x, int k, int Matrix_len);
LL num_pow(LL num, LL k);

int main(){
    LL a, b;
    int n;
    while(~scanf("%lld %lld %d", &a, &b, &n)){
        if(n == 0){
            printf("%lld\n", a%mod);
            continue;
        }
        if(n == 1){
            printf("%lld\n", b%mod);
            continue;
        }
        Matrix x;
        x.v[0][0] = 1, x.v[0][1] = 1;
        x.v[1][0] = 1, x.v[1][1] = 0;
        Matrix y = matrix_pow(x, n-2, 2);

        LL t1 = (y.v[0][0] + y.v[0][1])%(mod-1);
        LL t2 = (y.v[1][0] + y.v[1][1])%(mod-1);

        LL ans1 = num_pow(b, t1);
        LL ans2 = num_pow(a, t2);
        LL ans = ans1*ans2%mod;
        printf("%lld\n", ans);
    }
    return 0;
}
Matrix multiply(const Matrix &a, const Matrix &b, int Matrix_len){
    Matrix tmp;
    memset(tmp.v, 0, sizeof(tmp.v));
    for(int i = 0; i < Matrix_len; i++){
        for(int j = 0; j < Matrix_len; j++){
            for(int k = 0; k < Matrix_len; k++){
                tmp.v[i][j] += (a.v[i][k]*b.v[k][j]);
                tmp.v[i][j] %= (mod-1);
            }
        }
    }
    return tmp;
}
Matrix matrix_pow(Matrix &x, int k, int Matrix_len){
    Matrix tmp;
    memset(tmp.v, 0, sizeof(tmp.v));
    for(int i = 0; i < Matrix_len; i++)
        tmp.v[i][i] = 1;
    while(k){
        if(k & 1)
            tmp = multiply(tmp, x, Matrix_len);
        x = multiply(x, x, Matrix_len);
        k >>= 1;
    }
    return tmp;
}
LL num_pow(LL num, LL k){
    LL ans = 1;
    while(k){
        if(k & 1)
            ans = ans*num%mod;
        num = num*num%mod;
        k >>= 1;
    }
    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值