HDU 4549 M斐波那契數列(矩陣快速冪+歐拉定理)


M斐波那契數列

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 353    Accepted Submission(s): 93


Problem Description
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
 

 

Source
 

 

Recommend
liuyiding
 
 
這題的話,看a ,b 的指數,剛好可以使用斐波那契數列求解。
 
然后用矩陣做。
 
A^B %C   這題的C是質素,而且A,C是互質的。
所以直接A^(B%(C-1)) %C
 
比較一般的結論是 A^B %C=A^( B%phi(C)+phi(C) ) %C     B>=phi(C)
 
 
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;
const int MOD=1e9+7;

struct Matrix
{
    long long mat[2][2];
};
Matrix mul(Matrix a,Matrix b)
{
    Matrix ret;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
        {
            ret.mat[i][j]=0;
            for(int k=0;k<2;k++)
            {
                ret.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                ret.mat[i][j]%=(MOD-1);
            }
        }
    return ret;
}
Matrix pow_M(Matrix a,int n)
{
    Matrix ret;
    memset(ret.mat,0,sizeof(ret.mat));
    ret.mat[0][0]=ret.mat[1][1]=1;
    Matrix temp=a;
    while(n)
    {
        if(n&1)ret=mul(ret,temp);
        temp=mul(temp,temp);
        n>>=1;
    }
    return ret;
}
long long pow_m(long long a,long long n)
{
    long long ret=1;
    long long temp=a%MOD;
    while(n)
    {
        if(n&1)
        {
            ret*=temp;
            ret%=MOD;
        }
        temp*=temp;
        temp%=MOD;
        n>>=1;
    }
    return ret;
}
int main()
{
    int a,b,n;
    Matrix tmp;
    tmp.mat[0][0]=0;
    tmp.mat[0][1]=tmp.mat[1][0]=tmp.mat[1][1]=1;
    while(scanf("%d%d%d",&a,&b,&n)==3)
    {
        Matrix p=pow_M(tmp,n);
        //printf("%d %d %d %d\n",p.mat[0][0],p.mat[1][0],p.mat[0][1],p.mat[1][1]);
        int ans=(pow_m(a,p.mat[0][0])*pow_m(b,p.mat[1][0]))%MOD;
        printf("%d\n",ans);
    }
    return 0;
}

 

 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM