Java – Check Prime Number
Write a Java program to check a given number is a prime number or not.
What is a Prime Number?
- A prime number is a number that is fully divisible by itself or 1 only.
- Such as 13 is a prime number, it is not fully divisible by any number from 2-12.
You may like:
Example
This is a sample Java program to check 13 is a prime number or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class CheckPrimeNumber { public static void main(String[] args) { int num = 13; boolean isPrime = true; for (int i=2; i <= num/2; i++) { if ( num % i == 0) { isPrime = false; break; } } if ( isPrime == true ) System.out.println(num + "is a prime number"); else System.out.println(num + "is not a prime number"); } } |
Compile and run this program:
javac CheckPrimeNumber.java java CheckPrimeNumber
Output:
13 is a prime number
Check Prime Number with User Input
The following Java program will prompt a user to input a number and check if the entered number is a prime number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.util.Scanner; public class CheckPrimeNumber { private static Scanner scanner = new Scanner( System.in ); public static void main(String[] args) { System.out.println("Input a number: "); String input = scanner.nextLine(); int num = Integer.parseInt( input ); boolean isPrime = true; for (int i=2; i <= num/2; i++) { if ( num % i == 0) { isPrime = false; break; } } if ( isPrime == true ) System.out.println("Yes " + num + " is a prime number"); else System.out.println("No " + num + " is not a prime number"); } } |
Compile and run this program:
javac CheckPrimeNumber.java java CheckPrimeNumber
Output:
Input a number: 13 Yes 13 is a prime number
Again run:
Input a number: 15 No 15 is not a prime number