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输入包含多组测试数据;
F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )
现在给出a, b, n,你能求出F[n]的值吗?
每组数据占一行,包含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 2Sample Output
0 60
思路详情:
https://www.cnblogs.com/kuangbin/archive/2013/05/21/3090793.html(解答程序干了什么)
https://www.cnblogs.com/huxianglin/p/5995649.html(解答程序的数学问题)
AC C++:
#include <cstring>
#include <cstdio>
const int MOD=1e9+7;
struct Matrix
{
long long mat[2][2];
Matrix()
{
memset(mat,0,sizeof(mat));
}
//构造函数在程序开始时自动执行
//与之相反地是析构函数,在程序结束时自动执行,函数前有“~”。
};
Matrix mul(Matrix a,Matrix b)
{
Matrix result;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
{
result.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
result.mat[i][j]%=(MOD-1);
//运用了费马小定理,所以是 MOD-1 ,不是MOD
}
return result;
}
Matrix pow_Mat(Matrix a,int n)
{
Matrix result;
result.mat[0][0]=result.mat[1][1]=1;
//先把结果矩阵写成 I 矩阵
Matrix temp=a;
while(n)
{
if(n&1)result=mul(result,temp);
temp=mul(temp,temp);
n>>=1;
}
return result;
}
long long pow_mum(long long a,long long n)
{
long long result=1;
long long temp=a%MOD;
while(n)
{
if(n&1)
{
result*=temp;
result%=MOD;
}
temp*=temp;
temp%=MOD;
n>>=1;
}
//这个地方时正常取余,所以是MOD
return result;
}
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)
//scanf()函数返回值是 :成功赋值的数据项数
{
Matrix p=pow_Mat(tmp,n);
int ans=(pow_mum(a,p.mat[0][0])*pow_mum(b,p.mat[1][0]))%MOD;
//因为斐波那契的第一项是1,第零项 是 0,所以刚好两个矩阵相乘最终结果就是2*2矩阵的第一列
printf("%d\n",ans);
}
return 0;
}