Java Program to Check the Prime Number or Not
This article is created to cover a program in Java that checks whether a number entered by the user is a prime number or not. I've used the following two
ways to do the job:
- Using the "for" loop, check the prime number.
- Using the "while" loop, check the prime number.
Note: A prime number is a number that can only be divisible by 1 and the number itself. For example, 2, 3, 5, 7, 11, etc.
Check the prime number in Java using the for loop
The question is, should I write a Java program to check the prime number or not use a for loop? The user must receive the number during program execution.
The program given below has its answer:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int num, i, count=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number: ");
num = s.nextInt();
for(i=2; i<num; i++)
{
if(num%i == 0)
{
count++;
break;
}
}
if(count==0)
System.out.println("\nIt is a Prime Number.");
else
System.out.println("\nIt is not a Prime Number.");
}
}
The snapshot given below shows the sample run of the above Java program with user input at 19:
Since the number 19 can only be divisible by 1 and the number itself (19) without leaving any remainder, therefore, 19 is a prime number.
Check the prime number in Java using the while loop
This program is created using the while loop. Also, the program is modified in a way that it will print the number along with a message saying
whether it is prime or not. Let's have a look at the program given below:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int num, i=2, count=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number: ");
num = s.nextInt();
while(i<num)
{
if(num%i == 0)
{
count++;
break;
}
i++;
}
if(count==0)
System.out.println("\n" +num+ " is a Prime Number.");
else
System.out.println("\n" +num+ " is not a Prime Number.");
}
}
Here is its sample run with user input, 12:
12 is not a prime number because, except for 1, the numbers 2, 3, 4, and 6 also divide 12.
Same Program in Other Languages
Java Online Test
« Previous Program
Next Program »