BigInteger nextProbablePrime() Method in Java with Examples
Last Updated :
08 Apr, 2019
The java.math.BigInteger.nextProbablePrime() is used to find the first integer greater than this BigInteger that is probably prime. If this method returns ‘p’ then there is no prime number ‘q’ between this Biginteger and ‘p’ (this < q < p ) i.e. it never skips any prime number greater than BigInteger that is used to call the method.
Syntax:
public BigInteger nextProbablePrime()
Parameters: The method doesn’t accept any Parameters.
Return: This method returns a Biginteger which holds the first integer greater than this BigInteger that is probably prime number.
Exception: The number must be non – negative and not too large otherwise Arithmetic Exception is thrown.
Below programs illustrate nextProbablePrime() method of BigInteger class
Example 1:
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
BigInteger result;
String input1 = "1516132" ;
BigInteger a
= new BigInteger(input1);
result = a.nextProbablePrime();
System.out.println( "The next probable"
+ " Prime number is "
+ result);
}
}
|
Output:
The next probable Prime number is 1516153
Example 2: Printing all Prime number below 100
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
BigInteger result;
BigInteger a;
for ( int i = 0 ; i < 100 😉 {
a = new BigInteger(
Integer.toString(i));
result = a.nextProbablePrime();
if (Integer.parseInt(
result.toString())
< 100 ) {
System.out.print(result + " " );
}
i = Integer.parseInt(
result.toString());
}
}
}
|
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Example 3: Program showing exception when value is negative.
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
BigInteger result;
String input1 = "-5" ;
BigInteger a
= new BigInteger(input1);
try {
result = a.nextProbablePrime();
}
catch (ArithmeticException e) {
System.out.println(e);
}
}
}
|
Output:
java.lang.ArithmeticException: start < 0: -5
To know about checking current BigInteger is prime or not, visit isProbablePrime() Method in Java page.
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#nextProbablePrime()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...