就是个矩阵二分幂吧
#include<iostream>
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<math.h>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
#define MAXN 4
#define ll long long
const ll INF=0x3f7f7f7f;
ll mod;
class Matrix
{
public:
ll a[MAXN][MAXN];
Matrix()
{
memset(a,0,sizeof(a));
}
Matrix(ll x)
{
memset(a,0,sizeof(a));
if(x==1)
for(ll i=0;i<MAXN;i++)
a[i][i]=1;
}
Matrix operator +(const Matrix &b)const
{
Matrix temp;
for(ll i=1;i<MAXN;i++)
{
for(ll j=1;j<MAXN;j++)
{
temp.a[i][j]=(a[i][j]+b.a[i][j])%(mod-1);
}
}
return temp;
}
Matrix operator -(const Matrix &b)const
{
Matrix temp;
for(ll i=1;i<MAXN;i++)
{
for(ll j=1;j<MAXN;j++)
{
temp.a[i][j]=a[i][j]-b.a[i][j];
}
}
return temp;
}
Matrix operator *(const Matrix &b)const
{
Matrix temp;
for(ll i=1;i<MAXN;i++)
{
for(ll j=1;j<MAXN;j++)
{
for(ll k=1;k<MAXN;k++)
{
temp.a[i][j]+=(a[i][k]*b.a[k][j])%(mod-1);
temp.a[i][j]%=(mod-1);
//cout<<temp.a[i][j]<<"****";
}
}
}
return temp;
}
Matrix mat_pow(Matrix x,ll n)
{
Matrix ans(1);
while(n)
{
if(n%2)
{
ans=ans*x;
//ans%=mod;
}
x=x*x;
n>>=1;
}
return ans;
}
};
ll get(ll x,ll y)
{
ll ans=1;
while(y)
{
if(y%2)
ans=(ans*x)%mod;
y>>=1;
x=(x*x)%mod;
}
return ans%mod;
}
ll t,s,b,c,p,n;
int main()
{
scanf("%lld",&t);
while(t--)
{
Matrix x,y;
scanf("%lld%lld%lld%lld%lld",&n,&s,&b,&c,&p);
mod=p;
if(n==1)
{
puts("1");
continue;
}
else if(s%p==0)
{
puts("0");
continue;
}
else if(n==2)
{
printf("%lld\n",get(s,b));
continue;
}
x.a[1][1]=c;x.a[1][2]=1;x.a[1][3]=1;
x.a[2][1]=1;
x.a[3][3]=1;
y.a[1][1]=b;
y.a[2][1]=0;
y.a[3][1]=b;
x=x.mat_pow(x,n-2);
x=x*y;
ll temp=x.a[1][1]%mod;
temp=get(s,temp)%mod;
printf("%lld\n",temp);
}
return 0;
}