Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/math/BigInteger/PrimeTest.java
38821 views
1
/*
2
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
/*
27
* @test
28
* @bug 8026236
29
* @summary test primality verification methods in BigInteger
30
* @author bpb
31
* @key randomness
32
*/
33
import java.math.BigInteger;
34
import java.util.BitSet;
35
import java.util.List;
36
import java.util.NavigableSet;
37
import java.util.SplittableRandom;
38
import java.util.TreeSet;
39
import static java.util.stream.Collectors.toCollection;
40
import static java.util.stream.Collectors.toList;
41
import java.util.stream.IntStream;
42
import java.util.stream.Stream;
43
44
public class PrimeTest {
45
46
private static final int DEFAULT_UPPER_BOUND = 1299709; // 100000th prime
47
private static final int DEFAULT_CERTAINTY = 100;
48
private static final int NUM_NON_PRIMES = 10000;
49
50
/**
51
* Run the test.
52
*
53
* @param args The parameters.
54
* @throws Exception on failure
55
*/
56
public static void main(String[] args) throws Exception {
57
// Prepare arguments
58
int upperBound = args.length > 0 ? Integer.valueOf(args[0]) : DEFAULT_UPPER_BOUND;
59
int certainty = args.length > 1 ? Integer.valueOf(args[1]) : DEFAULT_CERTAINTY;
60
boolean parallel = args.length > 2 ? Boolean.valueOf(args[2]) : true;
61
62
// Echo parameter settings
63
System.out.println("Upper bound = " + upperBound
64
+ "\nCertainty = " + certainty
65
+ "\nParallel = " + parallel);
66
67
// Get primes through specified bound (inclusive) and Integer.MAX_VALUE
68
NavigableSet<BigInteger> primes = getPrimes(upperBound);
69
70
// Check whether known primes are identified as such
71
boolean primeTest = checkPrime(primes, certainty, parallel);
72
System.out.println("Prime test result: " + (primeTest ? "SUCCESS" : "FAILURE"));
73
if (!primeTest) {
74
System.err.println("Prime test failed");
75
}
76
77
// Check whether known non-primes are not identified as primes
78
boolean nonPrimeTest = checkNonPrime(primes, certainty);
79
System.out.println("Non-prime test result: " + (nonPrimeTest ? "SUCCESS" : "FAILURE"));
80
81
if (!primeTest || !nonPrimeTest) {
82
throw new Exception("PrimeTest FAILED!");
83
}
84
85
System.out.println("PrimeTest succeeded!");
86
}
87
88
/**
89
* Create a {@code BitSet} wherein a set bit indicates the corresponding
90
* index plus 2 is prime. That is, if bit N is set, then the integer N + 2
91
* is prime. The values 0 and 1 are intentionally excluded. See the
92
* <a
93
* href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_description">
94
* Sieve of Eratosthenes</a> algorithm description for more information.
95
*
96
* @param upperBound The maximum prime to allow
97
* @return bits indicating which indexes represent primes
98
*/
99
private static BitSet createPrimes(int upperBound) {
100
int nbits = upperBound - 1;
101
BitSet bs = new BitSet(nbits);
102
for (int p = 2; p * p < upperBound;) {
103
for (int i = p * p; i < nbits + 2; i += p) {
104
bs.set(i - 2, true);
105
}
106
do {
107
++p;
108
} while (p > 1 && bs.get(p - 2));
109
}
110
bs.flip(0, nbits);
111
return bs;
112
}
113
114
/**
115
* Load the primes up to the specified bound (inclusive) into a
116
* {@code NavigableSet}, appending the prime {@code Integer.MAX_VALUE}.
117
*
118
* @param upperBound The maximum prime to allow
119
* @return a set of primes
120
*/
121
private static NavigableSet<BigInteger> getPrimes(int upperBound) {
122
BitSet bs = createPrimes(upperBound);
123
NavigableSet<BigInteger> primes = bs.stream()
124
.mapToObj(p -> BigInteger.valueOf(p + 2))
125
.collect(toCollection(TreeSet::new));
126
primes.add(BigInteger.valueOf(Integer.MAX_VALUE));
127
System.out.println(String.format("Created %d primes", primes.size()));
128
return primes;
129
}
130
131
/**
132
* Verifies whether the fraction of probable primes detected is at least 1 -
133
* 1/2^certainty.
134
*
135
* @return true if and only if the test succeeds
136
*/
137
private static boolean checkPrime(NavigableSet<BigInteger> primes,
138
int certainty,
139
boolean parallel) {
140
long probablePrimes = (parallel ? primes.parallelStream() : primes.stream())
141
.filter(bi -> bi.isProbablePrime(certainty))
142
.count();
143
144
// N = certainty / 2
145
// Success if p/t >= 1 - 1/4^N
146
// or (p/t)*4^N >= 4^N - 1
147
// or p*4^N >= t*(4^N - 1)
148
BigInteger p = BigInteger.valueOf(probablePrimes);
149
BigInteger t = BigInteger.valueOf(primes.size());
150
BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2);
151
BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE);
152
BigInteger left = p.multiply(fourToTheC);
153
BigInteger right = t.multiply(fourToTheCMinusOne);
154
155
if (left.compareTo(right) < 0) {
156
System.err.println("Probable prime certainty test failed.");
157
}
158
159
return left.compareTo(right) >= 0;
160
}
161
162
/**
163
* Verifies whether all {@code BigInteger}s in the tested range for which
164
* {@code isProbablePrime()} returns {@code false} are <i>not</i>
165
* prime numbers.
166
*
167
* @return true if and only if the test succeeds
168
*/
169
private static boolean checkNonPrime(NavigableSet<BigInteger> primes,
170
int certainty) {
171
int maxPrime = DEFAULT_UPPER_BOUND;
172
try {
173
maxPrime = primes.last().intValueExact();
174
} catch (ArithmeticException e) {
175
// ignore it
176
}
177
178
// Create a list of non-prime BigIntegers.
179
List<BigInteger> nonPrimeBigInts = (new SplittableRandom())
180
.ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf)
181
.filter(b -> !b.isProbablePrime(certainty)).collect(toList());
182
183
// If there are any non-probable primes also in the primes list then fail.
184
boolean failed = nonPrimeBigInts.stream().anyMatch(primes::contains);
185
186
// In the event, print which purported non-primes were actually prime.
187
if (failed) {
188
for (BigInteger bigInt : nonPrimeBigInts) {
189
if (primes.contains(bigInt)) {
190
System.err.println("Prime value thought to be non-prime: " + bigInt);
191
}
192
}
193
}
194
195
return !failed;
196
}
197
}
198
199