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.
Below is Java program to demonstrate above function.
// A Java program to check if a number is prime using // inbuilt function import java.util.*; import java.math.*; 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)); } } |
Output:
true
Below is Java program to demonstrate above function.
// 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)); } } |
Output:
17
This article is contributed by Ayush Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Check if a prime number can be expressed as sum of two Prime Numbers
- Check whether the sum of prime elements of the array is prime or not
- Find coordinates of a prime number in a Prime Spiral
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Print the nearest prime number formed by adding prime numbers to N
- Print prime numbers with prime sum of digits in an array
- Check n^2 - m^2 is prime or not
- Check if N is Strong Prime
- Check if N is a Factorial Prime
- Sum of prime numbers without odd prime digits
- Check if a number is Full Prime
- Check whether the given number is Wagstaff prime or not
- Check a number for Permutable Prime
- Check whether N is a Dihedral Prime Number or not
- Check whether the given numbers are Cousin prime or not



