hdu4549——M斐波那契數列(費馬小定理+矩陣快速冪)

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

可以推出f(n)=a^fib(n-1)*b^fib(n),n>=2
然後根據費馬小定理a^n = a^( n%(p-1) )求得
所以要先求出用矩陣快速冪求出fib數列,再用快速冪求a^n,最後乘起來就行了

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h>
#include <algorithm>
#include <queue>
#include <iomanip>
#define INF 0x3f3f3f3f
#define MAXN 10000005
#define Mod 1000000007
using namespace std;
const int N = 2;
long long m,n;
struct Matrix
{
    long long mat[N][N];
};
Matrix mul(Matrix a,Matrix b)
{
    Matrix res;
    for(int i=0; i<2; ++i)
        for(int j=0; j<2; ++j)
        {
            res.mat[i][j]=0;
            for(int k=0; k<2; ++k)
            {
                res.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                res.mat[i][j]%=(Mod-1);
            }
        }
    return res;
}
Matrix pow_matrix(Matrix a,long long k)
{
    Matrix res;
    memset(res.mat,0,sizeof(res.mat));
    for(int i=0; i<2; ++i)
        res.mat[i][i]=1;
    while(k)
    {
        if(k%2)
            res=mul(res,a);
        a=mul(a,a);
        k>>=1;
    }
    return res;
}
long long pow_mod(long long a,long long k)
{
    long long res=1;
    while(k)
    {
        if(k%2)
            res=(res*a)%Mod;
        a=(a*a)%Mod;
        k>>=1;
    }
    return res;
}
int main()
{
    Matrix tmp;
    long long a,b;
    while(~scanf("%I64d%I64d%I64d",&a,&b,&n))
    {
        memset(tmp.mat,0,sizeof(tmp.mat));
        tmp.mat[0][0]=tmp.mat[1][0]=tmp.mat[0][1]=1;
        if(n==0)
        {
            printf("%I64d\n",a);
            continue;
        }
        Matrix p=pow_matrix(tmp,n-1);
        long long ans;
        ans=(pow_mod(a,p.mat[1][0])*pow_mod(b,p.mat[0][0]))%Mod;
        printf("%I64d\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章