Q. Java program to Check Whether a Number is Prime or not.

Here you will find an algorithm and program in Java programming language to check whether the given number is prime number or not. First let us understand what prime number means.

Explanation : A number that is divisible by only and only 1 and itself is known as a Prime Number. For example: - 11 is only divisible by 1, so 11 is prime, while 10 is divisible by 1, 2, and 5 so 10 is not a prime number.

Prime Number Algorithm

START
  Step 1 → Take integer variable A
  Step 2 → Divide the variable A with (A/2 to 2)
  Step 3 → If A is divisible by any value (A/2 to 2) then it is not prime
  Step 4 → Else it is prime number
STOP


Java Program to Check Whether a Number is Prime or Not

import java.util.Scanner;
class PrimeCheck
{
	public static void main(String args[])
	{    
		int temp;
		boolean isPrime=true;
		Scanner scan= new Scanner(System.in);
		System.out.println("Enter a positive number:");
		int num=scan.nextInt();
		scan.close();
		for(int i=2;i<=num/2;i++)
		{
			temp=num%i;
			if(temp==0)
			{
				isPrime=false;
				break;
			}
		}
		if(isPrime)
			System.out.println(num + " is a Prime Number");
		else
			System.out.println(num + " is not a Prime Number");
	}
}

Output

Enter a positive integer : 17
17 is a prime number.
Enter a positive integer : 25
25 is not a prime number.