BigInteger Probable Prime Test

Test primality with BigInteger.isProbablePrime and walk to the next prime, clarifying what the certainty argument does and does not promise.

JavaSecurity Boundaries

Code

snippet
import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger candidate = new BigInteger("1000000007");

        // certainty bounds the chance that a composite passes the test
        System.out.println("isProbablePrime: " + candidate.isProbablePrime(50));
        System.out.println("nextProbablePrime: " + candidate.nextProbablePrime());

        BigInteger composite = new BigInteger("1000000008");
        System.out.println("composite: " + composite.isProbablePrime(50));

        // small values are still checked by the same probable-prime routine
        StringBuilder primes = new StringBuilder();
        for (int n = 2; n <= 20; n++) {
            BigInteger value = BigInteger.valueOf(n);
            if (value.isProbablePrime(100)) {
                primes.append(n).append(' ');
            }
        }
        System.out.println("primes <= 20: " + primes.toString().trim());
    }
}

How it works

One way to read it: the class Main and the function main, doing all the work.

for (int n = 2; n <= 20; n++) is the loop that carries the per-item work.

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: public static void main(String[] args)

The run emits 3 labeled sections — isProbablePrime:, nextProbablePrime:, composite: — one per step.

Key statements

BigInteger candidate = new BigInteger("1000000007");
BigInteger composite = new BigInteger("1000000008");
StringBuilder primes = new StringBuilder();

Interactive Tools for This Topic

FAQ

What does BigInteger Probable Prime Test print when run?
Execute the whole file; each printed line is prefixed with a label like `isProbablePrime:`, `nextProbablePrime:`, `composite:`.