题目链接:点击这里
fib数列和g数列可以用 O ( l o g n ) O(logn) O(logn) 矩阵快速幂求解。
根据费马小定理,由于 1e9+7 是素数,有 a 1 e 9 + 6 ≡ 1 ( m o d 1 e 9 + 7 ) {a\mathop{ {}}\nolimits^{ {1e9+6{\text{ }}}} \equiv 1 \left( mod\text{ }1e9+7 \right) } a1e9+6 ≡1(mod 1e9+7) 。因此幂的指数对1e9+6取模即可。
(a + b) % p = (a % p + b % p) % p (1)
(a - b) % p = (a % p - b % p) % p (2)
(a * b) % p = (a % p * b % p) % p (3)
a^b % p = ((a % p)^b) % p (4)
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const ll mod = 1e9+6;
struct matrix {
ll m[3][3];
};
matrix Mul(matrix A, matrix B)
{
matrix ret;
for(int i = 0; i < 3; i++) //枚举行
{
for(int j = 0; j < 3; j++) //枚举列
{
ret.m[i][j] = 0;
for(int k = 0; k < 3; k++)
ret.m[i][j] = (ret.m[i][j] + A.m[i][k] * B.m[k][j]) % mod; //取模1e9+6
}
}
return ret;
}
matrix Pow(matrix A, ll n)
{
matrix ret;
ret.m[0][0] = 1; //单位矩阵
ret.m[0][1] = 0;
ret.m[0][2] = 0;
ret.m[1][0] = 0;
ret.m[1][1] = 1;
ret.m[1][2] = 0;
ret.m[2][0] = 0;
ret.m[2][1] = 0;
ret.m[2][2] = 1;
while(n)
{
if(n&1)
ret = Mul(ret,A);
A = Mul(A,A);
n>>=1;
}
return ret;
}
ll g(ll n) //求g数列的第n项
{
matrix ans, A;
A.m[0][0] = 1;
A.m[0][1] = 1;
A.m[0][2] = 1;
A.m[1][0] = 1;
A.m[1][1] = 0;
A.m[1][2] = 0;
A.m[2][0] = 0;
A.m[2][1] = 0;
A.m[2][2] = 1;
ans = Pow(A, n-1);
return (ans.m[0][0] + ans.m[0][2]) % mod; //取模1e9+6
}
matrix fibMul(matrix A, matrix B)
{
matrix ret;
for(int i = 0; i < 2; i++) //枚举行
{
for(int j = 0; j < 2; j++) //枚举列
{
ret.m[i][j] = 0;
for(int k = 0; k < 2; k++)
ret.m[i][j] = (ret.m[i][j] + A.m[i][k] * B.m[k][j]) % mod; //取模1e9+6
}
}
return ret;
}
matrix fibPow(matrix A, ll n)
{
matrix ret;
ret.m[0][0] = 1; //单位矩阵
ret.m[0][1] = 0;
ret.m[1][0] = 0;
ret.m[1][1] = 1;
while(n)
{
if(n&1)
ret = fibMul(ret,A);
A = fibMul(A,A);
n>>=1;
}
return ret;
}
ll fib(ll n) //求斐波那契数列的第n项
{
matrix ans, A;
A.m[0][0] = 1;
A.m[0][1] = 1;
A.m[1][0] = 1;
A.m[1][1] = 0;
ans = fibPow(A, n-1);
return ans.m[0][0] % mod; //取模1e9+6
}
ll power(ll a, ll b, ll m)
{
ll res = 1;
while(b)
{
if(b&1)
res = res*a%m;
a = a*a%m;
b >>= 1;
}
return res;
}
int main()
{
ll m = 1e9+7;
ll n, x, y, a, b;
cin>>n>>x>>y>>a>>b;
if(n==1)
{
cout<<x%m<<endl;
return 0;
}
if(n==2)
{
cout<<y%m<<endl;
return 0;
}
if(x%m==0||y%m==0||a%m==0)
{
cout<<0;
return 0;
}
a = power(a%m, b, m);
cout<<power(x%m, fib(n-2), m)%m * power(y%m, fib(n-1), m)%m * power(a%m, g(n-2), m)%m<<endl;
return 0;
}