How to check if a number is prime in Java
In this Answer, we will discuss how to check whether a given number is prime or not in Java.
Before that, let’s go over what a prime number is.
All numbers that are greater than one and have only two divisors, i.e., and the number itself, are identified as prime numbers. We can also understand a prime number as a number that has exactly two divisors.
For example, let’s take the numbers two through eleven:
Number | Divisible By | Prime? |
2 | 1,2 | Yes |
3 | 1,3 | Yes |
4 | 1,2,4 | No |
5 | 1,5 | Yes |
6 | 1,2,3,6 | No |
7 | 1,7 | Yes |
8 | 1,2,4,8 | No |
9 | 1,3,9 | No |
10 | 1,2,5,10 | No |
11 | 1,11 | Yes |
Two, three, five, seven, and eleven are numbers that have exactly two divisors, i.e., one and the respective number itself, so they are prime numbers.
The isPrime() function
We will use the user-defined isPrime() function in Java, which takes the number as input and returns true if the number is prime and false if it is not.
Using for loop
- Take a number as input.
- Check if there is a divisor of the number in the range of to because two is the smallest prime number.
- There is no number that can be completely divided by more than half of the number itself. We need to loop through two to the number itself divided by two ().
- If any divisor is found, then the number is not prime; otherwise, the given number is prime.
Code
Let’s look at an example that takes a number as input and returns a string that states whether the number is a prime number or a non-prime number. Enter a number in the input section and then press the ‘RUN’ button.
import java.util.Scanner;class Prime {public static void main(String[] args) {Scanner sc= new Scanner(System.in);int number= sc.nextInt();if(isPrime(number)) {System.out.println(number + " is prime number");}else{System.out.println(number + " is a non-prime number");}}static boolean isPrime(int num){if(num<=1){return false;}for(int i=2;i<=num/2;i++){if((num%i)==0)return false;}return true;}}
Enter the input below
Explanation
-
Line 1: We import the
java.util.Scannerlibrary to read input from the user. -
Line 6: We take the input from the user and store it in a variable of
inttypenumberusing theScannerclass of Java. -
Line 7: We call the
isPrime()function and pass the taken number as a parameter. This function returnstrueif the number is prime; otherwise, it returnsfalse. The output will be printed based on what the function returns. -
Lines 14–26: We define the
isPrime()function. InsideisPrime(), we first check if the number is less than or equal to one, and if the condition is satisfied, then it simply returnsfalse. -
Lines 21–25: We run a
forloop from to , and if any divisor of the number is found, then it returnsfalse(the number is not prime). -
Line 25: After we end the loop, it returns
truebecause we do not find any divisor of the number.
Using recursion
Let's look at another example that takes a number as input and returns a string that states whether the number is a prime number or a non-prime number using the recursion. Enter a number in the input section and then press the 'RUN' button.
import java.util.Scanner;class Prime {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter a number: ");int number = sc.nextInt();if (isPrime(number, 2)) {System.out.println(number + " is a prime number");} else {System.out.println(number + " is not a prime number");}}static boolean isPrime(int num, int divisor) {if (num <= 1) {return false;}if (divisor > Math.sqrt(num)) {return true;}if (num % divisor == 0) {return false;}return isPrime(num, divisor + 1);}}
Enter the input below
Code explanation
-
Line 8: This line checks if the entered number is prime by calling the
isPrimemethod with the number and an initial divisor of2. -
Lines 16–18: This line checks if the
numis less than or equal to1, consider it non-prime. -
Lines 19–21: This line checks if the
divisorexceeds the square root of the number, in which case it returnstruebecause no divisor has been found, and the number is prime. -
Line 25: It is a recursive call to the
isPrimemethod with an incrementeddivisorto continue checking for primality.
This way, we can check whether the given number is prime or not in Java.
Practice
Let's test yourself by converting the following for loop code into the while loop. Here's the code snippet using a for loop:
import java.util.Scanner;class Prime {public static void main(String[] args) {Scanner sc= new Scanner(System.in);int number= sc.nextInt();if(isPrime(number)) {System.out.println(number + " is prime number");}else{System.out.println(number + " is a non-prime number");}}static boolean isPrime(int num){if(num<=1){return false;}for(int i=2;i<=num/2;i++){if((num%i)==0)return false;}return true;}}
Enter the input below
If you want to learn this task in different languages such as C++, Dart, or Python. Please visit the following Answers on our platform: