#include<bits/stdc++.h> using namespace std; typedef long long ll; const int S=8; ll mult_mod(ll a,ll b,ll c) { a%=c; b%=c; ll ret=0,tmp=a; while (b) { if (b&1) { ret+=tmp; if (ret>c) { ret-=c; } } tmp<<=1; if (tmp>c) tmp-=c; b>>=1; } return ret; } ll pow_mod(ll a,ll n,ll mod) { ll ret=1; ll temp=a%mod; while (n) { if(n&1) { ret=mult_mod(ret,temp,mod); } temp=mult_mod(temp,temp,mod); n>>=1; } return ret; } bool check(ll a,ll n,ll x,ll t) { ll ret=pow_mod(a,x,n); ll last=ret; for (int i=1; i<=t; i++) { ret=mult_mod(ret,ret,n); if (ret==1&&last!=1&&last!=n-1) { return 1; } last=ret; } if (ret!=1) { return 1; } return 0; } bool Miller_Rabin(ll n) { if (n<2) { return 0; } if (n==2) { return 1; } if ((n&1)==0) { return 0; } ll x=n-1; ll t=0; while ((x&1)==0) { x>>=1; t++; } srand(time(NULL)); for (int i=0; i<S; i++) { ll a=rand()%(n-1)+1; if (check(a,n,x,t)) { return 0; } } return 1; } ll factor[100]; int tol; ll gcd(ll a,ll b) { if (!b) { return a; } return gcd(b,a%b); } ll pollard_rho(ll x,ll c) { ll i=1,k=2; srand(time(NULL)); ll x0=rand()%(x-1)+1; ll y=x0; while (1) { i++; x0=(mult_mod(x0,x0,x)+c)%x; ll d=gcd(y-x0,x); if (d!=1&&d!=x) { return d; } if (y==x0) { return x; } if (i==k) { y=x0; k+=k; } } } __int128 quick(__int128 a,__int128 b,__int128 p) { __int128 ret=1%p; while (b) { if (b&1) { ret=ret*a%p; } b>>=1; a=a*a%p; } return ret; } void findfac(ll n,ll k) { if (n==1) { return; } if (Miller_Rabin(n)) { factor[tol++]=n; return; } ll p=n; ll c=k; while (p>=n) { p=pollard_rho(p,c--); } findfac(p,k); findfac(n/p,k); } __int128 inv(__int128 a,__int128 p){ return quick(a,p-2,p); } int main() { ll t,p,prime; __int128 ans; scanf("%lld",&t); while (t--) { scanf("%lld",&p); for (ll i=p-1; i>=2; i--) { if (Miller_Rabin(i)) { prime=i; break; } } ans=p-1; for (__int128 i=p-1;i>prime;i--){ ans=ans*inv(i,p)%p; } printf("%lld\n",(ll)ans); } }
原文地址:https://www.cnblogs.com/Accpted/p/11265726.html
时间: 2024-10-11 07:21:54