Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/math/BigInteger/PrimeTest.java
41149 views
1
/*
2
* Copyright (c) 2014, 2017, 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.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
/*
25
* @test
26
* @library /test/lib
27
* @build jdk.test.lib.RandomFactory
28
* @run main PrimeTest
29
* @bug 8026236 8074460 8078672
30
* @summary test primality verification methods in BigInteger (use -Dseed=X to set PRNG seed)
31
* @author bpb
32
* @key randomness
33
*/
34
import java.math.BigInteger;
35
import java.util.BitSet;
36
import java.util.List;
37
import java.util.NavigableSet;
38
import java.util.Set;
39
import java.util.SplittableRandom;
40
import java.util.TreeSet;
41
import jdk.test.lib.RandomFactory;
42
import static java.util.stream.Collectors.toCollection;
43
import static java.util.stream.Collectors.toList;
44
45
public class PrimeTest {
46
47
private static final int DEFAULT_UPPER_BOUND = 1299709; // 100000th prime
48
private static final int DEFAULT_CERTAINTY = 100;
49
private static final int NUM_NON_PRIMES = 10000;
50
51
/**
52
* Run the test.
53
*
54
* @param args The parameters.
55
* @throws Exception on failure
56
*/
57
public static void main(String[] args) throws Exception {
58
// Prepare arguments
59
int upperBound = args.length > 0 ? Integer.valueOf(args[0]) : DEFAULT_UPPER_BOUND;
60
int certainty = args.length > 1 ? Integer.valueOf(args[1]) : DEFAULT_CERTAINTY;
61
boolean parallel = args.length > 2 ? Boolean.valueOf(args[2]) : true;
62
63
// Echo parameter settings
64
System.out.println("Upper bound = " + upperBound
65
+ "\nCertainty = " + certainty
66
+ "\nParallel = " + parallel);
67
68
// Get primes through specified bound (inclusive) and Integer.MAX_VALUE
69
NavigableSet<BigInteger> primes = getPrimes(upperBound);
70
71
// Check whether known primes are identified as such
72
boolean primeTest = checkPrime(primes, certainty, parallel);
73
System.out.println("Prime test result: " + (primeTest ? "SUCCESS" : "FAILURE"));
74
if (!primeTest) {
75
System.err.println("Prime test failed");
76
}
77
78
// Check whether known non-primes are not identified as primes
79
boolean nonPrimeTest = checkNonPrime(primes, certainty);
80
System.out.println("Non-prime test result: " + (nonPrimeTest ? "SUCCESS" : "FAILURE"));
81
82
boolean mersennePrimeTest = checkMersennePrimes(certainty);
83
System.out.println("Mersenne test result: " + (mersennePrimeTest ? "SUCCESS" : "FAILURE"));
84
85
if (!primeTest || !nonPrimeTest || !mersennePrimeTest) {
86
throw new Exception("PrimeTest FAILED!");
87
}
88
89
System.out.println("PrimeTest succeeded!");
90
}
91
92
/**
93
* Create a {@code BitSet} wherein a set bit indicates the corresponding
94
* index plus 2 is prime. That is, if bit N is set, then the integer N + 2
95
* is prime. The values 0 and 1 are intentionally excluded. See the
96
* <a
97
* href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_description">
98
* Sieve of Eratosthenes</a> algorithm description for more information.
99
*
100
* @param upperBound The maximum prime to allow
101
* @return bits indicating which indexes represent primes
102
*/
103
private static BitSet createPrimes(int upperBound) {
104
int nbits = upperBound - 1;
105
BitSet bs = new BitSet(nbits);
106
for (int p = 2; p * p < upperBound;) {
107
for (int i = p * p; i < nbits + 2; i += p) {
108
bs.set(i - 2, true);
109
}
110
do {
111
++p;
112
} while (p > 1 && bs.get(p - 2));
113
}
114
bs.flip(0, nbits);
115
return bs;
116
}
117
118
/**
119
* Load the primes up to the specified bound (inclusive) into a
120
* {@code NavigableSet}, appending the prime {@code Integer.MAX_VALUE}.
121
*
122
* @param upperBound The maximum prime to allow
123
* @return a set of primes
124
*/
125
private static NavigableSet<BigInteger> getPrimes(int upperBound) {
126
BitSet bs = createPrimes(upperBound);
127
NavigableSet<BigInteger> primes = bs.stream()
128
.mapToObj(p -> BigInteger.valueOf(p + 2))
129
.collect(toCollection(TreeSet::new));
130
primes.add(BigInteger.valueOf(Integer.MAX_VALUE));
131
System.out.println(String.format("Created %d primes", primes.size()));
132
return primes;
133
}
134
135
/**
136
* Verifies whether the fraction of probable primes detected is at least 1 -
137
* 1/2^certainty.
138
*
139
* @return true if and only if the test succeeds
140
*/
141
private static boolean checkPrime(Set<BigInteger> primes,
142
int certainty,
143
boolean parallel) {
144
long probablePrimes = (parallel ? primes.parallelStream() : primes.stream())
145
.filter(bi -> bi.isProbablePrime(certainty))
146
.count();
147
148
// N = certainty / 2
149
// Success if p/t >= 1 - 1/4^N
150
// or (p/t)*4^N >= 4^N - 1
151
// or p*4^N >= t*(4^N - 1)
152
BigInteger p = BigInteger.valueOf(probablePrimes);
153
BigInteger t = BigInteger.valueOf(primes.size());
154
BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2);
155
BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE);
156
BigInteger left = p.multiply(fourToTheC);
157
BigInteger right = t.multiply(fourToTheCMinusOne);
158
159
if (left.compareTo(right) < 0) {
160
System.err.println("Probable prime certainty test failed");
161
}
162
163
return left.compareTo(right) >= 0;
164
}
165
166
/**
167
* Verifies whether all {@code BigInteger}s in the tested range for which
168
* {@code isProbablePrime()} returns {@code false} are <i>not</i>
169
* prime numbers.
170
*
171
* @return true if and only if the test succeeds
172
*/
173
private static boolean checkNonPrime(NavigableSet<BigInteger> primes,
174
int certainty) {
175
int maxPrime = DEFAULT_UPPER_BOUND;
176
try {
177
maxPrime = primes.last().intValueExact();
178
} catch (ArithmeticException e) {
179
// ignore it
180
}
181
182
// Create a list of non-prime BigIntegers.
183
SplittableRandom splitRandom = RandomFactory.getSplittableRandom();
184
List<BigInteger> nonPrimeBigInts = (splitRandom)
185
.ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf)
186
.filter(b -> !b.isProbablePrime(certainty)).collect(toList());
187
188
// If there are any non-probable primes also in the primes list then fail.
189
boolean failed = nonPrimeBigInts.stream().anyMatch(primes::contains);
190
191
// In the event, print which purported non-primes were actually prime.
192
if (failed) {
193
for (BigInteger bigInt : nonPrimeBigInts) {
194
if (primes.contains(bigInt)) {
195
System.err.println("Prime value thought to be non-prime: " + bigInt);
196
}
197
}
198
}
199
200
return !failed;
201
}
202
203
/**
204
* Verifies whether a specified subset of Mersenne primes are correctly
205
* identified as being prime. See
206
* <a href="https://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime</a>
207
* for more information.
208
*
209
* @return true if and only if the test succeeds
210
*/
211
private static boolean checkMersennePrimes(int certainty) {
212
int[] MERSENNE_EXPONENTS = {
213
2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
214
2281, 3217, 4253, // uncomment remaining array elements to make this test run a long time
215
/* 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497,
216
86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269,
217
2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951,
218
30402457, 32582657, 37156667, 42643801, 43112609, 57885161 */
219
};
220
System.out.println("Checking first "+MERSENNE_EXPONENTS.length+" Mersenne primes");
221
222
boolean result = true;
223
for (int n : MERSENNE_EXPONENTS) {
224
BigInteger mp = BigInteger.ONE.shiftLeft(n).subtract(BigInteger.ONE);
225
if (!mp.isProbablePrime(certainty)) {
226
System.err.println("Mp with p = "+n+" not classified as prime");
227
result = false;
228
}
229
}
230
231
return result;
232
}
233
}
234
235