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
思路:根据这个题目我们很容易想到这是一个和斐波那契有关的题,而斐波那契是加法运算,题目是乘法运算我们很容易联想到指数,因为幂运算指数做加法。又根据斐波那契数列的性质,我们很容易联想到矩阵快速幂
注意一点!!!由于是指数运算,要用费马小定理取模(mod - 1)
斐波那契数列的性质:
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
const int N =4e5 + 7;
const double ex = 1e-8;
typedef unsigned long long ull;
typedef long long ll;
typedef double dl;
struct Matrix{
ll v[2][2];
};
Matrix mul(Matrix a,Matrix b)
{
Matrix temp;
for(int i = 0;i < 2;++i)
for(int j = 0;j < 2;++j){
temp.v[i][j] = 0;
for(int k = 0;k < 2;++k){
temp.v[i][j] += a.v[i][k] * b.v[k][j];
temp.v[i][j] %= (mod - 1); //这个位置把卡了好久。。。
}
}
return temp;
}
Matrix fpow_Matrix(Matrix a,ll n)
{
Matrix temp;
temp.v[0][0] = temp.v[1][1] = 1;
temp.v[0][1] = temp.v[1][0] = 0;
while(n){
if(n & 1) temp = mul(temp,a);
a = mul(a,a);
n >>= 1;
}
return temp;
}
ll fpow_mod(ll a,ll b)
{
ll res = 1;
while(b){
if(b & 1) res = (res * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return res;
}
int main()
{
ll a,b,n;
while(scanf("%lld%lld%lld",&a,&b,&n) != EOF){
Matrix t,r;
t.v[0][0] = 0;
t.v[0][1] = t.v[1][0] = t.v[1][1] = 1;
r = fpow_Matrix(t,n);
ll ans = (fpow_mod(a,r.v[0][0]) * fpow_mod(b,r.v[1][0])) % mod;
printf("%lld\n",ans);
}
return 0;
}