Java Program to check whether a number is prime or not


April 15, 2022, Learn eTutorial
1380

Here we are explaining how to write a java program to check whether a number is prime or not.

What is a prime number?

A prime number is a number that can be exactly divided by 1 and that number itself.

Example:2 , 3 ,5, 7 etc.

Here 2 is divided by 1 and 2.

3 is divided by 1 and 3.

5 is divided by 1 and 5.

 

How to implement the java program to check whether a number is prime or not?

First, we have to declare the class PrimeNumber with a public modifier. Create an object of the scanner class as sc and read the integer number from the user into the variable num. Create a boolean variable flag and set it to false. By using a for loop, set i=2and check iN=num/2, Then check the condition for prime, that is check num mod i equals 0 or not. If it equal to zero then set flag=true and break. If flag not equals true, then display it as a prime number, else display it as not a prime number using System.out.println() function.

 

ALGORITHM

STEP 1: Declare the class PrimeNumber with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Read the number from the user into the variable num.

STEP 4: Declare flag as boolean variable and set to false.

STEP 5: By using a for loop set i=2,check i<=num/2,do step 6.

STEP 6: check if num mod i equals o or not, if it equal to zero then set flag=true and break.

STEP 7: Check if the flag not equal to true then display a number as a prime number.

STEP 8: Else display the number is not a prime number.

 

Java Source Code

                                          import java.util.Scanner;

public class PrimeNumber {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

      System.out.println("Enter the Number: ");
      int num= sc.nextInt();
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }

        if (!flag)
            System.out.println(num + " Is A Prime Number");
        else
            System.out.println(num + " Is Not A Prime Number");
    }
}
                                      

OUTPUT

Enter the Number: 7
7 Is A Prime Number