題目不難懂。式子是一個遞推式,並且不難發現f[n]都是a的整數次冪。(f[1]=a0;f[2]=ab;f[3]=ab*f[2]c*f[1]...)
我們先只看指數部分,設h[n]. 則
h[1]=0;
h[2]=b;
h[3]=b+h[2]*c+h[1];
h[n]=b+h[n-1]*c+h[n-1].
h[n]式三個數之和的遞推式,所以就可以轉化為3x3的矩陣與3x1的矩陣相乘。於是
h[n] c 1 b h[n-1]
h[n-1] = 1 0 0 * h[n-2]
1 0 0 1 1
又根據費馬小定理(ap-1%p=1,p是質數且a,p互質)可得:ah[n]%mod=ah[n]%(mod-1)%mod.
因為 ah[n]%mod= ax*(mod-1)+h[n]%(mod-1)%mod = ax*(mod-1)*ah[n]%(mod-1)%mod = ah[n]%(mod-1)%mod;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll p;
struct Mat
{
ll mat[3][3];
};
Mat Multiply(Mat a, Mat b)
{
Mat c;
memset(c.mat, 0, sizeof(c.mat));
for(int k = 0; k < 3; ++k)
for(int i = 0; i < 3; ++i)
if(a.mat[i][k])
for(int j = 0; j < 3; ++j)
if(b.mat[k][j])
c.mat[i][j] = (c.mat[i][j] +a.mat[i][k] * b.mat[k][j])%(p-1);
return c;
}
Mat QuickPower(Mat a, ll k)
{
Mat c;
memset(c.mat,0,sizeof(c.mat));
for(int i = 0; i <3; ++i)
c.mat[i][i]=1;
for(; k; k >>= 1)
{
if(k&1) c = Multiply(c,a);
a = Multiply(a,a);
}
return c;
}
ll Powermod(ll a,ll b)
{
a%=p;
ll ans=1;
for(; b; b>>=1)
{
if(b&1) ans=(ans*a)%p;
a=(a*a)%p;
}
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
ll n,a,b,c;
Mat x;
while(T--)
{
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p);
if(n==1)
printf("1\n");
else if(n==2)
printf("%I64d\n",Powermod(a,b));
else
{
x.mat[0][0]=c; x.mat[0][1]=1; x.mat[0][2]=b;
x.mat[1][0]=1; x.mat[1][1]=0; x.mat[1][2]=0;
x.mat[2][0]=0; x.mat[2][1]=0; x.mat[2][2]=1;
x=QuickPower(x,n-2);
ll k=(x.mat[0][0]*b+x.mat[0][2]);
printf("%I64d\n",Powermod(a,k));
}
}
return 0;
}