題目:http://acm.hdu.edu.cn/showproblem.php?pid=5667
題解:http://bestcoder.hdu.edu.cn/solutions.php?page=3
分析:根据题解化简找出那个行列式,然后就求gi。需要注意的是gi是指数,根据费马小定理,指数%(p-1)即可。
題解:http://bestcoder.hdu.edu.cn/solutions.php?page=3
分析:根据题解化简找出那个行列式,然后就求gi。需要注意的是gi是指数,根据费马小定理,指数%(p-1)即可。
a ^ b % c = a ^(b % phi(c) + phi(c)) % c; 因为c是质数,所以这里的phi就为c - 1;所以只要用矩阵幂的时候% c -1,答案% c即可
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
ll mod;
struct mat
{
ll m[3][3];
};
mat mul(mat a,mat b)
{
mat c;
memset(c.m,0,sizeof(c.m));
for(int k=0;k<3;k++)
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j]%(mod-1))%(mod-1);
return c;
}
mat qmod(mat a,ll k)
{
mat c;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)c.m[i][j]=(i==j);
for(;k;k>>=1){
if(k&1)c=mul(c,a);
a=mul(a,a);
}
return c;
}
ll po(ll x, ll k)
{
ll res = 1;
for(;k;k>>=1){
if(k&1)res=res*x%mod;
else x=x*x%mod;
}
return res;
}
int main()
{
//freopen("f.txt","r",stdin);
int T;
ll a,b,c, n;
scanf("%d",&T);
while(T--){
scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&mod);
if(n==1){
printf("1\n");continue;
}
else if(n==2){
ll res=po(a,b);
printf("%lld\n",res);continue;
}
mat ans;
ans.m[0][0]=c;ans.m[0][1]=1;ans.m[0][2]=0;
ans.m[1][0]=1;ans.m[1][1]=ans.m[1][2]=0;
ans.m[2][0]=b;ans.m[2][1]=0;ans.m[2][2]=1;
ans=qmod(ans,n-2);
ll res=1;
ll k=ans.m[0][0]*b+ans.m[2][0];
res=po(a,k);
printf("%lld\n",res);
}
return 0;
}