求最小原根 51nod 1135

Posted HITLJR

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求最小原根 51nod 1135相关的知识,希望对你有一定的参考价值。

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1135

代码

技术分享
// the smallest primitive root of prime P
#include <bits/stdc++.h>
const long long mod = 1e9+7;
const double ex = 1e-10;
#define inf 0x3f3f3f3f
using namespace std;
long long N;
int b[100005];
vector <int> p;
vector <int> c;
// quick multiply
long long quick_s(long long x,long long y)
{
    long long ans = 1;
    while (y){
        if (y % 2) ans = (ans * x) % N;
        x = (x*x) % N;
        y/=2;
    }
    return ans % N;
}
int main()
{
    cin >> N;
    memset(b,0,sizeof(b));
    // get the prime
    for (int i = 2;i<1e5;i++){
        if ( b[i] == 0 ){
            p.push_back(i);
            int j = 2;
            while (i*j < 1e5)
                b[i] = 1,j++;
        }
    }
    // get the factor of the N-1
    // save the N-1/factor
    long long t = N-1;
    for (int i = 0; i<p.size();++i){
        if (t % p[i]==0&&t != 1)
            c.push_back((N-1)/p[i]);
        while (t % p[i]==0&&t != 1) t/=p[i];
    }
    if (t != 1) c.push_back((N-1)/t);
    //enumeration 2 to N-1 to get the smallest
    int flag = 1;
    for (int i = 2; i<=N-1;i++)
    {
        flag = 1;
        for (int j = 0 ; j < c.size() ;++j) // if the smallest number k make i^k mod N is N-1 then it is the primitive root
            if (quick_s(i,c[j]) == 1&&c[j]!=N-1) flag = 0;
        if (flag && (quick_s(i,N-1)==1)) {
            cout << i<<endl;
            return 0;
        }
    }
    return 0;
}
View Code

 

以上是关于求最小原根 51nod 1135的主要内容,如果未能解决你的问题,请参考以下文章

[51nod1135] 原根

[51nod1135]原根

51nod 1135 原根

(数论)51NOD 1135 原根

51nod 1135 原根

51NOD 1135 原根