1. 程式人生 > >求最小原根 51nod 1135

求最小原根 51nod 1135

back clas save size flag con cout sin hide

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