Write a Program to check Prime numbers or Not


This Java program checks if a given number is a prime number or not. A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. The program starts by importing the Scanner class, which allows the program to read input from the user. The program then creates an instance of the Scanner class and prompts the user to enter a number. The program reads the input number using the nextInt() method of the Scanner class and stores it in the integer variable num.

Next, the program calculates the value of a as half of the input number (num) and initializes two integer variables, i and flag, to 2 and 0 respectively. The variable a is used as an upper limit for the loop that checks for prime factors, and the variable flag is used to determine whether the input number is prime or not.

The program then enters an if-else statement that checks if the input number is 0, 1, or any other number. If the input number is 0 or 1, the program prints a message indicating that the number is not a prime number. Otherwise, the program enters a for loop that runs from 2 to a, checking if each value is a factor of the input number by checking if num is divisible by i using the modulo operator (%). If i is a factor of num, the program sets flag to 1, prints a message indicating that the number is not a prime number, and breaks out of the loop.

If the input number is not divisible by any value of i, the program sets flag to 0 and prints a message indicating that the number is a prime number.

Source Code

import java.util.Scanner;
class Prime_Number
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The number :");
		int num = input.nextInt();
		int i,a=0,flag=0; 
		a=num/2;      
		if(num==0||num==1)
		{
			System.out.println(num+" is Not Prime Number");      
		}
		else
		{
			for(i=2;i<=a;i++)
			{
				if(num%i==0)
				{
				 System.out.println(num+" is Not Prime Number");
				 flag=1;      
				 break;      
				}
			}
			if(flag==0)
			{ 
				System.out.println(num+" is Prime Number");
			}
		}
	}
}  

Output

Enter The number :71
71 is Prime Number

Example Programs