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;
}