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
分析:写出前几项
f0=a
f1=b
f2=a * b
f3=a * b2
f4=a2 * b3
…
(a b后面是指数)
发现指数为斐波那契数列 a的指数fn-1 b的指数fn
费马小定理:C为质数且A,C互质,A^B %C=A^(B%(C-1))%C (欧拉函数定理:n是个素数 它的欧拉函数为n-1)
运用矩阵快速幂和快速幂求解
最后输出(quick_pow(a,ans.m[1][1])*quick_pow(b,ans.m[1][0]))%mod
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod=1000000007;
ll a,b,n,num1,num2,sum;
struct mat{
ll m[2][2];
}c,ans;
ll quick_pow(ll a,ll b)
{
ll temp=a%mod,ans=1;
while(b)
{
if(b&1)
ans=(ans*temp)%mod;
temp=(temp*temp)%mod;
b>>=1;
}
return ans%mod;
}
mat mul(mat a,mat b)
{
mat temp;
memset(temp.m,0,sizeof(temp.m));
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
for(int k=0;k<2;k++)
{
temp.m[i][j]=(temp.m[i][j]+a.m[i][k]*b.m[k][j])%(mod-1);
}
}
}
return temp;
}
void pow_mat(ll n)
{
memset(ans.m,0,sizeof(ans.m));
for(int i=0;i<2;i++)
ans.m[i][i]=1;
c.m[0][0]=1;
c.m[0][1]=1;
c.m[1][0]=1;
c.m[1][1]=0;
while(n)
{
if(n&1)
ans=mul(ans,c);
c=mul(c,c);
n>>=1;
}
// cout<<ans.m[1][1]<<" "<<ans.m[1][0]<<endl;
// cout<<a<<" "<<b<<endl;
printf("%lld\n",(quick_pow(a,ans.m[1][1])*quick_pow(b,ans.m[1][0]))%mod);
}
int main()
{
while(~scanf("%lld %lld %lld",&a,&b,&n))
{
if(n==0)
printf("%lld\n",a%mod);
else if(n==1)
printf("%lld\n",b%mod);
else
{
pow_mat(n);
}
}
return 0;
}