booleanprimeToCertainty(int certainty, Random random){ int rounds = 0; int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
// The relationship between the certainty and the number of rounds // we perform is given in the draft standard ANSI X9.80, "PRIME // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". int sizeInBits = this.bitLength(); if (sizeInBits < 100) { rounds = 50; rounds = n < rounds ? n : rounds; return passesMillerRabin(rounds, random); }
public boolean isProbablePrime(int certainty) (可调用)
参数certainty,若<0,直接返回true
特判2,2之外的偶数以及1。
其他使用primeToCertainty测试。
注意:MillerRabin素数测试的测试次数为(certainty+1)/2
kuangbin模板上面MillerRabin算法推荐测试次数为8-10次,对应参数为15-19。
注意:只有数字长度<100,才会只使用MillerRabin测试,且最多测试50次。
1 2 3 4 5 6 7 8 9 10 11
publicbooleanisProbablePrime(int certainty){ if (certainty <= 0) returntrue; BigInteger w = this.abs(); if (w.equals(TWO)) returntrue; if (!w.testBit(0) || w.equals(ONE)) returnfalse;
privatestatic Scanner scan = new Scanner(new BufferedInputStream(System.in)); publicstaticvoidmain(String[] args){ while(scan.hasNext()) { int n = scan.nextInt(); int ans = 0; for (int i = 0; i < n; ++ i) { int x = scan.nextInt(); if(BigInteger.valueOf(x).isProbablePrime(15)) ++ ans; } System.out.println(ans); } } }