Quick ways to check for Prime and find next Prime in Java
Many programming contest problems are somehow related Prime Numbers. Either we are required to check Prime Numbers, or we are asked to perform certain functions for all prime number between 1 to N. Example: Calculate the sum of all prime numbers between 1 and 1000000. Java provides two function under java.math.BigInteger to deal with Prime Numbers.
- isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime. For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite. Below is Java program to demonstrate above function.
Java
import java.util.*;
import java.math.*;
public class CheckPrimeTest
{
static boolean checkPrime( long n)
{
BigInteger b = new BigInteger(String.valueOf(n));
return b.isProbablePrime( 1 );
}
public static void main (String[] args)
throws java.lang.Exception
{
long n = 13 ;
System.out.println(checkPrime(n));
}
}
|
Time Complexity: O(1).
The time complexity of this algorithm is O(1), since the BigInteger.isProbablePrime() method takes constant time to check the primality of a number.
Space Complexity: O(1).
The space complexity of this algorithm is also O(1). We only use a single variable to store the number, which is constant space.
- nextProbablePrime() : Another method present in BigInteger class. This functions returns the next Prime Number greater than current BigInteger. Below is Java program to demonstrate above function.
Java
import java.util.*;
import java.math.*;
class NextPrimeTest
{
static long nextPrime( long n)
{
BigInteger b = new BigInteger(String.valueOf(n));
return Long.parseLong(b.nextProbablePrime().toString());
}
public static void main (String[] args)
throws java.lang.Exception
{
long n = 14 ;
System.out.println(nextPrime(n));
}
}
|
Time complexity: O(1)
Space complexity: O(1)
Last Updated :
28 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...