Last Updated : 23 Jul, 2025
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.
// A Java program to check if a number is prime using
// inbuilt function
import java.util.*;
import java.math.*;
public class CheckPrimeTest
{
//Function to check and return prime numbers
static boolean checkPrime(long n)
{
// Converting long to BigInteger
BigInteger b = new BigInteger(String.valueOf(n));
return b.isProbablePrime(1);
}
// Driver method
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.
// Java program to find prime number greater than a
// given number using built in method
import java.util.*;
import java.math.*;
class NextPrimeTest
{
// Function to get nextPrimeNumber
static long nextPrime(long n)
{
BigInteger b = new BigInteger(String.valueOf(n));
return Long.parseLong(b.nextProbablePrime().toString());
}
// Driver method
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)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4