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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.