Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Check Whether a Number is Prime or Not


In this article, we will understand how to check whether a number is prime or not. Prime numbers are special numbers who have only two factors 1 and itself and cannot be divided by any other number. A number is a prime number if its only factors are 1 and itself. 11 is a prime number. Its factors are 1 and 11 itself. Some examples of prime numbers are 2, 3, 5, 7, 11, 13 and so on. 2 is the only even prime number. All other prime numbers are odd numbers.

Below is a demonstration of the same −

Input

Suppose our input is −

Enter the number : 47

Output

The desired output would be −

The number 47 is a prime number.

Algorithm

Step 1 - START
Step 2 - Declare a integer value namely my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 - Using a for loop, check if the number is divisible by any of its lower numbers except 1. If no, it is a prime number. Else it’s not a prime number.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool Java Program to Check Whether a Number is Prime or Not.

import java.util.Scanner;
public class IsPrime {
   public static void main(String[] args) {
      int my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      boolean isprime = false;
      for (int i = 2; i <= my_input / 2; ++i) {
         if (my_input % i == 0) {
            isprime = true;
            break;
         }
      }
      if (!isprime)
         System.out.println("The number " +my_input + " is a prime number.");
      else
         System.out.println("The number " +my_input + " is not a prime number.");
   }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 47
The number 47 is a prime number.

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class IsPrime {
   public static void main(String[] args) {
      int my_input = 47;
      System.out.println("The number is defined as " +my_input);
      boolean isprime = false;
      for (int i = 2; i <= my_input / 2; ++i) {
         if (my_input % i == 0) {
            isprime = true;
            break;
         }
      }
      if (!isprime)
         System.out.println("The number " +my_input + " is a prime number.");
      else
         System.out.println("The number " +my_input + " is not a prime number.");
   }
}

Output

The number is defined as 47
The number 47 is a prime number.