M斐波那契数列
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 4729 Accepted Submission(s): 1473
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]的值吗?
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 )
每组数据占一行,包含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
题解:
a^x*b^y,x,y是斐波那契数列的某一项,可以用矩阵快速幂求解,
然后不能对指数直接取余,根据费马小定理,如果b,与p互质,则有
a^b%p=a^(b%(p-1))%p;这样就可以先求解出指数取模p-1的值,然后
用快速幂求解即可。
代码:
#include<bits/stdc++.h>
using namespace std;
const int mod=1000000007;
#define ll long long
struct node
{
ll mx[2][2];
}a,b;
node cheng(node A,node B)
{
node temp;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
temp.mx[i][j]=0;
for(int k=0;k<2;k++)
{
temp.mx[i][j]+=A.mx[i][k]*B.mx[k][j];
temp.mx[i][j]%=(mod-1);
}
}
return temp;
}
void mtpow(ll b1)
{
a.mx[0][0]=1;a.mx[0][1]=1;
a.mx[1][0]=1;a.mx[1][1]=0;
while(b1)
{
if(b1&1)b=cheng(a,b);
a=cheng(a,a);
b1=b1/2;
}
}
ll pow1(ll a1,ll b1)
{
ll r=1;
while(b1)
{
if(b1&1)r=r*a1%mod;
a1=a1*a1%mod;
b1=b1/2;
}
return r;
}
int main()
{
ll x,y,z;
while(~scanf("%lld%lld%lld",&x,&y,&z))
{
b.mx[0][0]=1;b.mx[1][0]=1;
if(z==0)printf("%lld\n",x);
else if(z==1)printf("%lld\n",y);
else
{
mtpow(z-2);
ll X=pow1(y,b.mx[0][0]);
ll Y=pow1(x,b.mx[1][0]);
printf("%lld\n",X*Y%mod);
}
}
return 0;
}