The Preliminary Contest for ICPC Asia Nanjing 2019
B题:super_log
求
a
a
a
…
a
%
m
a^{a^{a^{…^a}}}\%m
aaa…a%m(b次a)
考虑欧拉降幂:
a
b
≡
a
b
%
φ
(
p
)
+
φ
(
p
)
m
o
d
p
(
b
≥
φ
(
p
)
)
a^b\equiv a^{b\%\varphi(p)+\varphi(p)}mod p(b\geq \varphi(p))
ab≡ab%φ(p)+φ(p)modp(b≥φ(p))
疯狂特判。。。。
#include<cstdio>
#define ll long long
using namespace std;
const int maxn = 1e6+10;
const ll N=1e18;
int T;
int phi[maxn],p[1000];
ll qpow(ll a,ll b,ll mod){
ll res=1;
while(b!=0){
if(b&1) res=res*a%mod;
a=a*a%mod;
b>>=1;
}
return res;
}
void phi_table(int N, int* phi) {
for (int i = 2; i <= N; i++) phi[i] = 0;
phi[1] = 1;
for (int i = 2; i <= N; i++)
if (!phi[i])
for (int j = i; j <= N; j += i) {
if (!phi[j]) phi[j] = j;
phi[j] = phi[j] / i * (i - 1);
}
}
bool check(int a,int b,int p){
if(b==0)return 1>=p;
if(b==1)return a>=p;
if(b==2){
if(a>=8)return true;
else return qpow(a,a,N)>=(ll)p;
}
if(a==1)return 1>=p;
if(a==2){
if(b==3)return 16>=p;
if(b==4)return 65536>=p;
else if(b>4)return true;
}
if(a>=3)return true;
}
ll f(int a,int b){
if(b==0)return 1;
else if(b==1)return a;
else {
if(a==1)return 1;
else{
return qpow((ll)a,f(a,b-1),N);
}
}
}
ll solve(int a,int b,int p){
if(p==1)return 0;
if(b==1)return a%p;
if(b==0)return 1%p;
if(check(a,b-1,phi[p])){
return qpow((ll)a,solve(a,b-1,phi[p])+phi[p],(ll)p);
}
return qpow((ll)a,f(a,b-1),(ll)p);
}
int main(){
int a,b,m;
phi_table(1000000,phi);
scanf("%d",&T);
while(T--){
scanf("%d%d%d",&a,&b,&m);
ll ans=solve(a,b,m);
printf("%lld\n",ans);
}
return 0;
}