直接贴大佬的博客吧:Qingo呀
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool issu(ll x){
for(ll i=2;i<=sqrt(x);++i)
if(x%i==0) return 0;
return 1;
}
ll ksc(ll x,ll y,ll mod) {
x%=mod;
y%=mod;
return (x*y-(ll)((long double)x/mod*y)*mod+mod)%mod;
}
ll quick(ll a,ll b,ll mod){
ll res=1;
while(b){
if(b&1) res=ksc(res,a,mod);
a=ksc(a,a,mod);
b>>=1;
}
return res;
}
int main(){
int t;
ll p;
scanf("%d",&t);
while(t--){
scanf("%lld",&p);
ll n=p-1;
while(1){
if(issu(n)) break;
--n;
}
ll ans=p-1;
for(ll i=n+1;i<=p-1;++i)
ans=ksc(ans,quick(i,p-2,p),p);
printf("%lld\n",ans);
}
return 0;
}