这个题是关于矩阵快速幂的一道题,只要结合一下费马小定理就可以了。
费马小定理:
a ^( p - 1) = 1 (mod p) p 为素数,且a 与 p互质
这题很明显可以推出f n = a ^( Fn ) ,同样 Fn 也是一个递推式
用公式 :a ^ (Fn % (p - 1)) = (a ^ Fn ) % p 结合矩阵快速幂就可以AC了,注意:a 与 p 不互质的情况。
代码:
#include<cstdio>
#include<iostream>
#include<map>
#include<stack>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std ;
#define LEN sizeof(struct node)
#define LLd long long int
const double PI = 3.1415926 ;
const double INF = 99999999 ;
const int MX =25 ;
LLd mod ;
class M{
public :
LLd p[3][3] ;
M(){
memset(p ,0 ,sizeof(p)) ;
}
void init(){
for(int i = 0 ;i < 3 ; ++i)
p[i][i] = 1 ;
}
M operator *(const M& a){
M c ;
for(int i = 0 ;i < 3 ; ++i)
for(int k = 0 ;k < 3 ; ++k)
if(p[i][k])
for(int j = 0 ;j < 3 ; ++j)
c.p[i][j] = (c.p[i][j] + (p[i][k]*a.p[k][j])%(mod-1))%(mod-1) ;
return c ;
}
} ;
M Matrix_Pow(M p ,LLd n){
M b ;
b.init() ;
while(n){
if(n&1)
b = b * p ;
n = n>>1 ;
p = p * p ;
}
return b ;
}
LLd Pow(LLd a ,LLd n){
LLd b = 1 ;
while(n){
if(n&1)
b = (b*a)%mod ;
n = n>>1 ;
a = (a*a)%mod ;
}
return b ;
}
int main(){
LLd T ,n ,a ,b ,c ;
cin>>T ;
while(T--){
cin>>n>>a>>b>>c>>mod ;
if(n == 1)
cout<<1<<endl ;
else if(n == 2)
cout<<Pow(a ,b)<<endl ;
else if(a%mod == 0)
cout<<0<<endl ;
else {
M t ;
t.p[0][0] = c ;
t.p[0][1] = t.p[1][0] = t.p[2][0] = t.p[2][2] = 1 ;
M d = Matrix_Pow(t ,n-2) ;
LLd ans ;
ans = ((b*d.p[0][0])%(mod-1) + (d.p[2][0]*b)%(mod-1))%(mod-1) ;
cout<<Pow(a ,ans)<<endl ;
}
}
return 0 ;
}