Enumeration displacement definitely times out. What we need for a displacement I is the number of cycles, that is, the number of gcd (I, n) and gcd (I, n, because it is equivalent to the number of N approx.
Therefore, we enumerate n's approx. For An approx K, that is, the number of loops such as N/K, there are Phi [k] types, proving that there are many online. So the answer is Phi [k] * (POW (N, N/K) (k is all the approx. N)
Since the number of arguments is large, you cannot create a table, but you can only calculate it for one.
Since we divide the last time by N, we cannot directly take the modulo if we do division. Therefore, when we calculate every POW (N, N/K), we will not multiply by one N, this is equivalent to Division.
#include<iostream>#include<cstdio>#include<cstdlib>#include<algorithm>#include<cstring>using namespace std;const int N=1000000;int quickpow(int m,int n,int k){ int ans=1; while(n) { if(n&1) ans=(ans*m)%k; n=(n>>1); m=(m*m)%k; } return ans;}bool a[N];int prim[N];int pp[N];void Prime(){ memset(a, 0, sizeof(a)); int num = 0, i, j; pp[1]=1; for(i = 2; i < N; ++i) { if(!(a[i])) prim[num++]=pp[i]=i; for(j = 0; (j<num && i*prim[j]<N); ++j) { pp[i*prim[j]]=prim[j]; a[i*prim[j]] = 1; if(!(i%prim[j])) break; } }}int phi(int x){ int i,j; int num = x; for(i = 0; prim[i]*prim[i] <= x; i++) { if(x % prim[i] == 0) { num = (num/prim[i])*(prim[i]-1); while(x % prim[i] == 0) { x = x / prim[i]; } } } if(x != 1) num = (num/x)*(x-1); return num;}int main(){ Prime(); int cas,n,p; scanf("%d",&cas); while(cas--) { int ans=0; scanf("%d%d",&n,&p); for(int l=1;l*l<=n;l++) { if(n%l==0) { if(l*l==n) { ans+=phi(l)%p*quickpow(n%p,l-1,p); ans%=p; break; } ans+=phi(l)%p*quickpow(n%p,n/l-1,p); ans+=phi(n/l)%p*quickpow(n%p,l-1,p); ans%=p; } } printf("%d\n",ans); } return 0;}