题解:P11961 [GESP202503 五级] 原根判断

· · 题解

P11961 原根判断

这道题的题意很明确,a 为质数 b 的原根有以下条件:

  1. a<b
  2. a^{b-1}≡1\left(\bmod\ b \right)
  3. 在 i=1 \sim b-1 中,只有 i=b-1 时满足 a^i≡1\left(\bmod\ b \right)

会数学的应该都知道,如果 a 和 b 如果不互质,则第二个条件就不行。

接着,我们知道其实后两条指的是 a 在模 b 意义下的阶是 b-1

我们还知道,a 在模 b 意义下的阶一定是 b-1 的因数,所以枚举即可。

code

#include<bits/stdc++.h>
#define int long long
using namespace std;
int qpow(int x,int y,int r){//快速幂,用来验证a是否满足条件2
    int res=1;
    while(y){
        if(y&1){
            res=(res*x)%r;
        }
        x=(x*x)%r;
        y>>=1;
    }
    return res;
}
signed main() {
    int t;
    cin>>t;
    while(t--){
        int a,p;
        cin>>a>>p;
        if(__gcd(a,p)!=1){
            cout<<"No"<<endl;
            continue;
        }
        int ans=2e9;
        p--;//减一方便后续操作
        for(int i=1;i*i<=p;i++){//枚举p-1的因数
            if(qpow(a,i,p+1)==1){//分别判断i和(p-1)/i是否满足条件
                ans=min(ans,i);//阶是因数中满足条件的最小值
            }
            if(qpow(a,p/i,p+1)==1){
                ans=min(ans,p/i);
            }
        }
        if(ans==p){//判断阶是否为p-1
            cout<<"Yes"<<endl;
        }else{
            cout<<"No"<<endl;
        }
    }
    return 0;
}