java.math.BigInteger isProbablePrime(int certainty)

Description

On this document we will be showing a java example on how to use the isProbablePrime(int certainty) method of BigInteger Class. Basically this method returns true if this BigInteger is probably prime, false if it’s definitely composite. If certainty is ≤ 0, true is returned. The certainty argument plays a big role in the consistency of the check if the number is prime, the higher the certainty the closer it will be that this BigInteger is a prime however the execution time is much higher. The execution time is proportional to the certainty provided.

Method Syntax

public boolean isProbablePrime(int certainty)

Method Argument

Data Type Parameter Description
int certainty a measure of the uncertainty that the caller is willing to tolerate: if the call returns true the probability that this BigInteger is prime exceeds (1 – 1/2certainty). The execution time of this method is proportional to the value of this parameter.

Method Returns

The isProbablePrime(int certainty) method returns true if this BigInteger is probably prime, false if it’s definitely composite.

Compatibility

Requires Java 1.1 and up

Java BigInteger isProbablePrime(int certainty) Example

Below is a java code demonstrates the use of isProbablePrime(int certainty) method of BigInteger class. The example presented might be simple however it shows the behavior of the isProbablePrime(int certainty) method.

package com.javatutorialhq.java.examples;

import java.math.BigInteger;
import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of isProbablePrime(int certainty) 
 * method of BigInteger class
 */

public class BigIntegerIsProbablePrimeExample {

	public static void main(String[] args) {	
		
		// get user input		 
		System.out.print("Enter a value:");
		Scanner s = new Scanner(System.in);
		String input = s.nextLine();
		System.out.print("Enter the certainty value:");
		String certaintyValue = s.nextLine();
		s.close();		

		// convert string input to BigInteger
		BigInteger val = new BigInteger(input);
		Integer certainty = Integer.parseInt(certaintyValue);
		// check if the number provided is prime number
		boolean result = val.isProbablePrime(certainty);
		if(result){
			System.out.println("Number provided is prime");
		}else{
			System.out.println("Number provided is composite");
		}

		
	}

}

This example is a lot simpler than it looks. Simply we ask for two user input. One is the number to be checked if its prime and the second one is the certainty. Afterwards we make use of the isProbablePrime method to check if the number provided is prime or not.

Sample Output

Below is the sample output when you run the above example.

BigInteger isProbablePrime() example output