June 22, 2022

Java Program to Check Whether Number Prime or Not

This post shows a Java program to check whether the passed number is a prime number or not.

A number is a prime number if can be divided either by 1 or by the number itself. So the logic for your program should be to run a for loop and divide the passed number every time in that loop, if it completely divides any time then the passed number is not a prime number. You only need to run your loop from 2 till N/2 (where N is the passed number), reason being no number is completely divisible by a number more than its half.

Java program to check whether the number is prime or not

import java.util.Scanner;

public class PrimeNumChecker {
  public static void main(String[] args) {
    // Using Scanner class to take input
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number - ");
    int num = sc.nextInt();
    boolean flag = isNumberPrime(num);
    if(flag){
      System.out.println(num + " is a prime number");
    }else{
      System.out.println(num + " is not a prime number");
    }
  }

  private static boolean isNumberPrime(int num){
    boolean flag = true;
    for(int i = 2; i <= num/2; i++){
      // No remainder means completely divides 
      if(num % i == 0){
        flag = false;
        break;
      }
    }
    return flag;
  }
}
Output
Enter number - 
7
7 is a prime number

Enter number - 
10
10 is not a prime number

That's all for the topic Java Program to Check Whether Number is Prime or Not. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment