HDU 4549 M斐波那契数列 (费马小定理+矩阵快速幂)






http://acm.hdu.edu.cn/showproblem.php?pid=4549







分析:

写出F[n]的几项之后发现a和b的指数和斐波那契数列有关     

具体的关系是      F[n]=a^fib[n-1] * b^fib[n]     

矩阵快速幂求fib    快速幂求a和b的n次幂

题目要求对F[n]%mod    这里用到费马小定理


即: 假如p是质数,且gcd(a,p)=1,那么 a(p-1)≡1(mod p),即:假如a是整数,p是质数,且a,p互质(即两者只有一个公约数1),那么a的(p-1)次方除以p的余数恒等于1    (来自百度百科)   


也就是说       ap %mod = ap%(mod-1)%mod


证明:

设 p=k*(mod-1)+r       

ap%mod=(ak*(mod-1) * ar)%mod=ar%mod=ap%(mod-1)%mod




AC代码:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <bitset>
#include <algorithm>
#include <climits>
typedef long long LL;
const LL mod=1000000007;
using namespace std;
int n=2;
struct Matrix{
    LL a[2][2];
    void init(){
        memset(a,0,sizeof(a));
        for (int i=0;i<n;i++)
            a[i][i]=1;
    }
};
Matrix multiply(Matrix x,Matrix y){
    Matrix temp;
    memset(temp.a,0,sizeof(temp.a));
    for (int i=0;i<n;i++){
        for (int j=0;j<n;j++){
            for (int k=0;k<n;k++){
                temp.a[i][j]=(temp.a[i][j]+x.a[i][k]*y.a[k][j])%(mod-1);
            }
        }
    }
    return temp;
}
Matrix qpow(Matrix M,LL k){
    Matrix temp;
    temp.init();
    while (k){
        if (k%2)
            temp=multiply(temp,M);
        k/=2;
        M=multiply(M,M);
    }
    return temp;
}
LL Power(LL a,LL b){
    LL temp=1;
    while (b){
        if(b%2)
            temp=(temp*a)%mod;
        b/=2;
        a=(a*a)%mod;
    }
    return temp%mod;
}
int main (){
    LL a,b,N;
    //freopen("data","r",stdin);
    while (scanf ("%lld%lld%lld",&a,&b,&N)!=EOF){
        Matrix M;
        memset(M.a,0,sizeof(M.a));
        M.a[0][0]=M.a[0][1]=M.a[1][0]=1;
        if (N==0){
            printf ("%lld\n",a);
            continue;
        }
        if (N==1){
            printf ("%lld\n",b);
            continue;
        }
        LL p1,p2;
        Matrix temp;
        temp=qpow(M,N-1);
        p1=temp.a[0][0];
        p2=temp.a[1][0];
        //printf ("%lld   %lld\n",p1,p2);
        printf("%lld\n",Power(a,p2)*Power(b,p1)%mod);
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值