- Java

Prime Number Program in Java

 In this post let’s how to find the given number by the user is prime or not. Usually, the prime number is a number which is divisible by one and by itself.

Note: 0 and 1 are not prime numbers. The 2 is the only even prime number because all the other even numbers can be divided by 2.

 Algorithm:

 1)Start
 2)Input the number from the user.
 3)Go on dividing the number starting from 2 to one unit lesser than the given number.
 4)Check whether the remainder of any number is zero.
 5)If the remainder is not zero continue the loop.
 6)If the remainder is zero display the given number is not prime.
 7)When the loop gets over the display that the given number is prime.


Code goes here:

import java.util.*;
class prime
{
 public static void main(String args[])
 {
  Scanner scan=new Scanner(System.in);
  int i,num;
  System.out.println("Enter the number to check whether prime or not");
  num=scan.nextInt(); //to take input from the user
  if(num==2) // if the number is two direct method
  {
   System.out.println("The given number is prime");
   System.exit(0);
  }
  for(i=2;i<num;i++)//checking whether the number is divisible by all numbers
  {
   if(num%i!=0) // if it is not divisible then continue the loop
    continue;
   else
   {
    System.out.println("The given number is not prime");
    System.exit(0);
   }
  }
  System.out.println("The given number is prime");// if it is not divisible come out of loop
}
}




Leave a Reply