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

M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?
Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )
Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。
Sample Input
0 1 0
6 10 2
Sample Output
0
60
分析: 先写出几项根据题意
0 a
1 b
2 a*b
3 a*b^2
4 a^2*b^3
5 a^3*b^5
….
规律很明显,除去前两项,从第三项开始关于a的幂的增长规律1 1 2 3 5 ….. 关于b的幂增长规律1 2 3 5 …. ,可以看到幂的增长呈斐波那契数列,b比a快一项。
最后的答案格式为 a ^ x * b ^ y %mod
n为1e9 这样到最后,第n项的x和y都是天数了,根本无法求。
所以这里用到了费马小定理降幂,因为mod>a mod>b,同时mod为素数,所以gcd(a,mod)==1,gcd(b,mod)==1条件满足,可以使用
我们可以先求a ^ x %mod 再求 b ^ y %mod
a=a ^ ( x % (mod-1 ) ) %mod ,b=b ^ ( y %(mod-1)) %mod
ans = a * b % mod ;

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>pii;
#define first fi
#define second se
#define  LL long long
#define fread() freopen("in.txt","r",stdin)
#define fwrite() freopen("out.txt","w",stdout)
#define CLOSE() ios_base::sync_with_stdio(false)

const int MAXN = 1e5;
const int MAXM = 1e6;
const int mod = 1e9+7 - 1 ;  // 
const int inf = 0x3f3f3f3f;

struct Matrix{
    LL a[5][5];
    int h,w;
}ori,res,it;

void init(){
    it.w=2,it.h=1;it.a[1][1]=1,it.a[1][2]=1;
    memset(res.a,0,sizeof(res.a));
    res.a[1][1]=res.a[2][2]=1;res.w=res.h=2;
    memset(ori.a,0,sizeof(ori.a));
    ori.w=ori.h=2;
    ori.a[1][1]=ori.a[1][2]=ori.a[2][1]=1;
}
Matrix mutil(Matrix a, Matrix b ){
    Matrix c;memset(c.a,0,sizeof(c.a));
    c.h=a.h,c.w=b.w;
    for(int i=1;i<=a.h;i++){
        for(int k=1;k<=a.w;k++){
            if(a.a[i][k]==0 ) continue;
            for(int j=1;j<=b.w;j++) 
                c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
        }
    }
    return c;
}
void  Matrix_mod(int n){
//  if(n<=1) return 1;
    n-=2;
    while(n){
        if(n&1) res=mutil(ori,res);
        ori=mutil(ori,ori);
        n>>=1;
    }
    res=mutil(it,res);
}

LL power(LL a,LL b,LL c){
    LL s=1,base=a%c;
    while(b){
        if(b&1) s=s*base%c;
        base=base*base%c;
        b>>=1;
    }
    return s;
}
int main(){
    CLOSE();
//  fread();
//  fwrite();
    LL a,b,n;
    while(scanf("%lld%lld%lld",&a,&b,&n)!=EOF){
        init();
        if(n==0)  printf("%lld\n",a);
        else if(n==1) printf("%lld\n",b);
        else {
            Matrix_mod(n);
            LL c=power(a,res.a[1][2],mod+1); 
            LL d=power(b,res.a[1][1],mod+1);
            //printf("%d%d\n",res.a[1][2],res.a[1][1]);
            printf("%lld\n",(c*d)%(mod+1));
         }
     } 
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值