on Leave a Comment

Java Program to Check Whether a number is Prime or Not

In this java program, we check whether a number is prime or not. A prime number is only divisible by 1 and itself.

Java Program to Check Whether a number is Prime or Not

public class PrimeNumber
{
 public static void main(String[] args)
 {
  int n = 83;
  boolean flag = false;
  for(int i = 2; i <= n/2; ++i)
  {            
     if(n % i == 0)
     {
       flag = true;
       break;
     }
  }
  if (!flag)
      System.out.println(n + " is a prime number.");
  else
      System.out.println(n + " is not a prime number.");
 }
}

OUTPUT:

83 is a prime number.

Java Program to Check Whether a number is Prime or Not Using Scanner

import java.util.*;
public class PrimeNumber
{
 public static void main(String[] args)
 {
  Scanner s = new Scanner(System.in);
  System.out.println("Enter a number ");
  int n = s.nextInt();
  boolean flag = false;
  for(int i = 2; i <= n/2; ++i)
  {
     if(n % i == 0)
     {
       flag = true;
       break;
     }
  }
  if (!flag)
     System.out.println(n + " is a prime number.");
  else
  System.out.println(n + " is not a prime number.");
 }
}

OUTPUT:

Enter a number

97

97 is a prime number.



0 comments:

Post a Comment