CF1027G X-mouse in the Campus
#include <bits/stdc++.h>
#define int long long
typedef long long ll;
const int N=1000005;
int m,a[N],f[N],p[N],n,cnt,x,ans;
std::map<int,int> id;
std::vector<int> v;
void init(){
for (int i=1;i*i<=m;i++)//所有因数
if (m%i==0){
a[++n]=i;
if (m/i!=i) a[++n]=m/i;
}
std::sort(a+1,a+n+1);
for (int i=1;i<=n;i++) id[a[i]]=i;
int x=m;
for (int i=2;i*i<=x;i++){
if (x%i) continue;
p[++cnt]=i;
while (x%i==0) x/=i;
}
if (x>1) p[++cnt]=x;
for (int i=1;i<=n;i++) f[i]=m/a[i];
for (int i=1;i<=cnt;i++)
for (int j=1;j<=n;j++)
if (a[j]%p[i]==0)
f[id[a[j]/p[i]]]-=f[j];
}
ll mul(ll x,ll y,ll mu){
x%=mu;
y%=mu;
ll ans=(x*y-(ll)((double)x*y/mu+0.1)*mu)%mu;
ans+=ans<0?mu:0;
return ans;
}
int ksm(int x,int y,int mu){
int ans=1;
x=x%mu;
for (;y;y>>=1,x=mul(x,x,mu))
if (y&1) ans=mul(x,ans,mu);
return ans;
}
bool MR(int n){
if (n==2 || n==3 || n==5 || n==7) return 1;
if (n%2==0 || n%3==0 || n%5==0 || n%7==0) return 0;
int T=12;
int d=n-1,k=0;
while (d%2==0) d>>=1,k++;
while (T--){
int x=rand();
x=ksm(x,d,n);
if (x==0) continue;
for (int i=1;i<=k;i++){
int t=x;
x=mul(x,x,n);
if (x==1 && (t!=1 && t!=n-1)) return 0;
}
if (x!=1) return 0;
}
return 1;
}
ll gcd(ll x,ll y){
if (x%y==0) return y;
return gcd(y,x%y);
}
int PR(int n){
if (n%2==0) return 2;
if (n%3==0) return 3;
int x=rand(),y=x,c=12,step=0,t=1;
while (++step){
y=(mul(y,y,n)+c)%n;
if (x==y) return n;
ll g=gcd((y-x+n)%n,n);
if (g>1) return g;
if (step==t) x=y,t<<=1;
}
}
void find(int n){
if (n==1) return;
if (MR(n)){
v.push_back(n);
return;
}
int d=n;
while (d==n || d==1) d=PR(n);
while (n%d==0) n/=d;
find(d);find(n);
}
signed main(){
srand(time(0));
scanf("%lld%lld",&m,&x);
init();
for (int i=1;i<n;i++){
int t=m/a[i],c=f[id[a[i]]];
v.clear();
find(c);
std::sort(v.begin(),v.end());
std::unique(v.begin(),v.end());
for (auto j:v)
while (c%j==0 && ksm(x,c/j,t)==1) c/=j;
ans=ans+f[i]/c;
}
printf("%lld\n",ans+1);
}
* 生而自由 爱而无畏 *