publicstaticvoidmain(String[] args)throws IOException { StreamTokenizerin=newStreamTokenizer(newBufferedReader(newInputStreamReader(System.in))); PrintWriterout=newPrintWriter(System.out); in.nextToken(); intp= (int) in.nval; divide(p - 1); for (intg=2; g < p; g++) { booleanflag=true; for (inti=0; i < sprime.size(); i++) { intt= (p - 1) / sprime.get(i); if (quickPowerMod(g, t, p) == 1) { flag = false; break; } } if (flag) { out.println(g); break;// 去掉break的话是求所有的原根,加上break是求最小的原根、 } } out.flush(); }
staticvoiddivide(int n) { // 将n分解为素因子 intt= (int) Math.sqrt(n); for (inti=0; prime.get(i) <= t; i++) { if (n % prime.get(i) == 0) { sprime.add(prime.get(i)); // 因为有可能有多个prime[i] while (n % prime.get(i) == 0) { n /= prime.get(i); } } } if (n > 1) { sprime.add(n);// 可能只有自己一个素因子 } }
staticlongquickPowerMod(long x, long n, long mod) { longresult=1; while (n > 0) { x = x % mod; if ((n & 1) != 0) result = result * x % mod; x = x * x % mod; n >>= 1; } return result; }
static ArrayList<Integer> getPrime(int n) { boolean[] notPrime = newboolean[n + 1]; intsqrtN= (int) Math.sqrt(n); for (inti=2; i <= sqrtN; i++) { if (notPrime[i]) continue; for (intj= i * i; j <= n; j += i) { // j是i的倍数,即不是素数 notPrime[j] = true; } }
ArrayList<Integer> prime = newArrayList<>(); if (n > 1) prime.add(2); for (inti=3; i <= n; i += 2) { if (notPrime[i]) continue; prime.add(i); } return prime; } }