求
b个a的次幂
解法:
对于
,我们可以直接使用欧拉降幂去求,但这个式子是a次幂,又该怎么办?
那么他的下一步一定还是递归的形式已知往下,直到q == 1 时,向上返回结果,所以只需在欧拉降幂的基础上加一个dfs
模板:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e6+100;
char b[maxn];
//欧拉函数
LL ouler(LL n){
LL ans = n, a = n;
for(LL i = 2; i * i <= a; i++){
if(a % i == 0){
ans -= ans / i;
while(a % i == 0){
a /= i;
}
}
}
if(a > 1){
ans -= ans / a;
}
return ans;
}
//快速幂
LL quick_mod(LL a, LL b, LL mod){
LL res = 1;
while(b){
if(b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
LL solve2(LL a, LL b, LL mod){
LL phi = ouler(mod);
if(b <= mod) return quick_mod(a, b, mod);
else{
a = a % phi;
return quick_mod(a, b+phi, mod);
}
}
LL solve(LL a, char b[], LL mod)
{
int len = strlen(b);
LL phi = ouler(mod);
LL tmp = 0;
for(int i = 0; i < len; i++){
tmp = tmp * 10 + (b[i] - '0');
if(tmp > mod) break;
}
if(tmp <= mod) return quick_mod(a, tmp, mod);
else{
tmp = 0;
for(int i = 0; i < len; i++)
tmp = ( tmp * 10 + (b[i] - '0') ) % phi;
return quick_mod(a, tmp + phi, mod);
}
}
LL ans = 0;
//递归的求2^(2^(2^(2.....)))
/*
int dfs(int p){
if(p == 1) return 1;
LL phi = ouler(p);
return quick_mod(2, dfs(phi) + phi, p);
}*/
//求a^(a^(a^(a^(a^...)))) b个a次幂
LL dfs(LL a, LL b, LL p)
{
if(p==1)
return 0;
if(b==0)
return 1;
LL phi=ouler(p);
LL tmp=dfs(a,b-1,phi);
if(tmp<=phi&&tmp)
return quick_mod(a,tmp,p);
else
return quick_mod(a,tmp+phi,p);
}
// A ^ B % p
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
LL a, b, m;
scanf("%lld%lld%lld",&a,&b,&m);
printf("%lld\n",dfs(a,b,m)%m);
}
return 0;
}