# HG changeset patch # User bpb # Date 1398794127 25200 # Tue Apr 29 10:55:27 2014 -0700 # Node ID 2d59787746414b37416ef3f21e4697bb60488257 # Parent 44fbb7e1a473f3ee7aabb900992c5c9cdbd5932c 8026236: Add PrimeTest for BigInteger Summary: Test primality verification methods in BigInteger Reviewed-by: TBD Contributed-by: Brian Burkhalter , Peter Levart , Paul Sandoz , Aleksey Shipilev , Florian Weimer diff --git a/test/java/math/BigInteger/PrimeTest.java b/test/java/math/BigInteger/PrimeTest.java new file mode 100644 --- /dev/null +++ b/test/java/math/BigInteger/PrimeTest.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8026236 + * @summary test primality verification methods in BigInteger + * @author bpb + */ +import java.io.FileNotFoundException; +import java.io.IOException; +import java.math.BigInteger; +import java.util.BitSet; +import java.util.NavigableSet; +import java.util.Random; +import java.util.TreeSet; +import java.util.stream.IntStream; +import static java.util.stream.Collectors.toCollection; + +public class PrimeTest { + + private static final int DEFAULT_UPPER_BOUND = 1299709; // 100000th prime + private static final int DEFAULT_CERTAINTY = 100; + private static final int NUM_NON_PRIMES = 10000; + + /** + * Run the test. + * + * @param args The parameters. + * @throws Exception on failure + */ + public static void main(String[] args) throws Exception { + // Prepare arguments + int upperBound = args.length > 1 ? Integer.valueOf(args[0]) : DEFAULT_UPPER_BOUND; + int certainty = args.length > 2 ? Integer.valueOf(args[1]) : DEFAULT_CERTAINTY; + boolean parallel = args.length > 3 ? Boolean.valueOf(args[2]) : true; + + // Echo parameter settings + System.out.println("upper bound = " + upperBound + + "\ncertainty = " + certainty + + "\nparallel = " + parallel); + + // Check whether known primes are identified as such + boolean primeTest = checkPrime(upperBound, certainty, parallel); + System.out.println("Prime test result: " + (primeTest ? "SUCCESS" : "FAILURE")); + if (!primeTest) { + System.err.println("Prime test failed"); + } + + // Check whether known non-primes are not identified as primes + boolean nonPrimeTest = checkNonPrime(upperBound, certainty); + System.out.println("Non-prime test result: " + (nonPrimeTest ? "SUCCESS" : "FAILURE")); + + if (!primeTest || !nonPrimeTest) { + throw new Exception("PrimeTest FAILED!"); + } + + System.out.println("PrimeTest succeeded!"); + } + + /** + * Create a {@code BitSet} wherein a set bit indicates the corresponding + * index is prime. + * @param upperBound The maximum prime to allow + * @return bits indicating which indexes represent primes + */ + private static BitSet primes(int upperBound) { + int nbits = upperBound + 1; + BitSet bs = new BitSet(nbits); + bs.set(0, 2, true); + for (int p = 2; p * p < upperBound;) { + for (int i = 2 * p; i < nbits; i += p) { + bs.set(i, true); + } + do { + ++p; + } while (bs.get(p)); + } + bs.flip(0, nbits); + return bs; + } + + /** + * Parse the primes up to the specified bound into a {@code NavigableSet}. + * @param upperBound The maximum prime to allow + * @return a set of primes + */ + private static NavigableSet parsePrimes(int upperBound) { + BitSet bs = primes(upperBound); + try (IntStream lines = bs.stream()) { + return lines.mapToObj(BigInteger::valueOf).collect(toCollection(TreeSet::new)); + } + } + + /** + * Verifies whether the fraction of probable primes detected is at least 1 - + * 1/2^certainty. + * + * @return true if and only if the test succeeds + */ + private static boolean checkPrime(int maxNumPrimes, + int certainty, + boolean parallel) { + + NavigableSet primes = parsePrimes(maxNumPrimes); + + System.out.println(String.format("Loaded %d primes", primes.size())); + + long probablePrimes = (parallel ? primes.parallelStream() : primes.stream()) + .filter(bi -> bi.isProbablePrime(certainty)) + .count(); + + System.out.println(probablePrimes + " probable primes out of " + + primes.size() + " candidates"); + if (probablePrimes != primes.size()) { + System.err.println("Number of probable primes unequal to number of actual primes"); + } + + // N = certainty / 2 + // Success if p/t >= 1 - 1/4^N + // or (p/t)*4^N >= 4^N - 1 + // or p*4^N >= t*(4^N - 1) + BigInteger p = BigInteger.valueOf(probablePrimes); + BigInteger t = BigInteger.valueOf(primes.size()); + BigInteger fourToTheC = BigInteger.valueOf(4).pow(certainty / 2); + BigInteger fourToTheCMinusOne = fourToTheC.subtract(BigInteger.ONE); + BigInteger left = p.multiply(fourToTheC); + BigInteger right = t.multiply(fourToTheCMinusOne); + + if (left.compareTo(right) < 0) { + System.err.println("Probable prime certainty test failed."); + } + + return left.compareTo(right) >= 0; + } + + /** + * Verifies whether all {@code BigInteger}s in the tested range for which + * {@code isProbablePrime()} returns {@code false} are not + * prime numbers. + * + * @return true if and only if the test succeeds + */ + private static boolean checkNonPrime(int maxNumPrimes, + int certainty) { + NavigableSet primes = parsePrimes(maxNumPrimes); + + int maxPrime = 100000; + try { + maxPrime = primes.last().intValueExact(); + } catch (ArithmeticException e) { + // ignore it + } + + // If it's not a probable prime but is in the primes list then fail. + boolean result = !(new Random()).ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf).filter(b -> !b.isProbablePrime(certainty)).anyMatch(primes::contains); + + return result; + } +}