a^b%c = a^(phi(c)+b%phi(c))%c

1e9看似吓人,其实中间模数为1时可以直接返回0,算是个强剪枝

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL pow(LL x, LL y, LL mod) {
LL ans = 1;
while (y) {
if (y & 1) ans = ans * x % mod;
x = x * x % mod;
y >>= 1;
}
return ans;
}
LL phi(LL x) {
LL ans = x;
for (LL i = 2; i*i <= x; i++) {
if (x % i == 0) {
ans = ans/i*(i-1);
while (x % i == 0) x /= i;
}
}
if (x > 1) ans = ans / x * (x-1);
return ans;
}
LL F(LL x, LL y) {
if (y == 1) return 0;
else if (x == 1) return 1 % y;
else if (x == 2) return 2 % y;
else if (x == 3) return 9 % y;
else if (x == 4) return 262144 % y;
LL t = phi(y);
return pow(x, t+F(x-1, t), y);
}
int main() {
LL n, m;
scanf("%lld%lld", &n, &m);
printf("%lld\n", F(n, m));
return 0;
}