则 一定存在原根 。
取原根 ,对同余式两边同时取离散对数,则只需要判断 。即 ,即 。
BSGS 暴力求时间是根号级别的,显然过不了。这个式子看起来很对称,考虑能不能转化为好求的东西。
考虑熟知的结论 ,对于 来说,。则 。即只需判断 即可。
#include<iostream>
#include<algorithm>
#include<random>
using ll=long long;
std::mt19937_64 rnd(0xb6e0);
ll qpow(ll base,ll exp,ll mod){
ll ans=1;
while(exp!=0){
if(exp&1)ans=(__int128_t)ans*base%mod;
base=(__int128_t)base*base%mod,exp>>=1;
}
return ans;
}
namespace Prime{
std::basic_string<int>base({2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71});
bool MillerRobin(ll p){
if(p==2)return true;
ll b=p-1,t=0;
while(b%2==0)b>>=1,t++;
for(int x:base){
if(p==x)return true;
ll r=qpow(2,b,p);
if(r==1||r==p-1)continue;
bool flag=false;
for(int j=1;j<=t&&!flag;j++){
r=(__int128_t)r*r%p;
if(r==p-1)flag=true;
}
if(!flag)return false;
}
return true;
}
ll PollardRho(ll n){
if(n%2==0)return 2;
ll x=0,y=x,k=1,c=rnd()%(n-1)+1,mul=1;
while(true){
for(int i=1;i<=k;i++){
x=((__int128)x*x%n+c)%n,mul=(__int128)mul*std::abs(x-y)%n;
if(x==y)break;
if(i%64==0){
ll d=std::__gcd(mul,n);
if(d>1)return d;
}
}
ll d=std::__gcd(mul,n);
if(d>1)return d;
y=x,k<<=1;
}
}
void getDivisor(ll p,std::basic_string<ll>&prime){
if(p==1)return;
if(MillerRobin(p))return prime+=p,void();
ll d=PollardRho(p);
while(d==1||d==p)d=PollardRho(p);
while(p%d==0)p/=d;
getDivisor(d,prime),getDivisor(p,prime);
}
}
ll phi(ll m){
std::basic_string<ll>prime;
Prime::getDivisor(m,prime);
std::sort(prime.begin(),prime.end());
prime.erase(std::unique(prime.begin(),prime.end()),prime.end());
ll ans=m;
for(ll p:prime)ans=ans/p*(p-1);
return ans;
}
std::basic_string<ll>prime;
ll ord(ll m,ll phi,ll a){
ll ans=phi;
for(ll p:prime)
while(ans%p==0&&qpow(a,ans/p,m)==1)ans/=p;
return ans;
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
ll m,phi;
int T;
std::cin>>m>>T,phi=::phi(m),Prime::getDivisor(phi,prime);
std::sort(prime.begin(),prime.end());
prime.erase(std::unique(prime.begin(),prime.end()),prime.end());
while(T--){
ll x,y;
std::cin>>x>>y;
std::cout<<(ord(m,phi,x)%ord(m,phi,y)==0?"Yes\n":"No\n");
}
return 0;
}