这道题题面很长(废话一堆), 但是总结就一句话题意:2^2^2^2……mod p
因为当 b > φ(p) 时,a ^ b ≡ a ^ (bmodφ(p) + φ(p))。所以我们可以递归地算这个式子,直到 p = 1。
即令f(p) = 2 ^ 2 ^ 2⋯ mod p,则有f(p) = 2^ (f(φ(p)) + φ(p)) mod p。
#include<cstdio> #include<algorithm> #include<iostream> #include<cmath> #define int long long typedef long long ll; using namespace std; const int maxn = 1e7 + 100; int get(ll x, int y, int z) { int cnt = 1; for(;y;(x *= x) %= z,y >>= 1) if(y & 1) (cnt *= x) %= z; return cnt; } signed phi[maxn]; ll solve(int p) { if(p == 1) return 0; return get(2,solve(phi[p]) + phi[p],p); } int t, p; signed main() { phi[1] = 1; for(signed i = 2;i < maxn;i++) if(!phi[i]) { for(signed j = i; j < maxn; j += i) { if(!phi[j]) phi[j] = j; phi[j] = phi[j] / i * (i - 1); } } for(scanf("%lld", &t);t--;) { scanf("%lld", &p); printf("%lld ",solve(p)); } return 0; }