Sunday, March 29, 2020

To check weather given number is prime or not in Java.

To check weather number is prime or not is simple. we need to take a number as a input and than we need run a for loop till the number-1 time and module each of the for loop variable with the number given. so by that if we get module = 0 , which means number can be devide and hence number is ot prime. 
import java.util.Scanner;

public class Primenumbers {

 public static void main(String[] args) {
  Scanner sc=new Scanner(System.in);
  System.out.println("enter the number->");
  int num=sc.nextInt();
  int flag=0;


  if(num==0||num==1)
  {
   System.out.println("please enter the valid number");
  }
  else
   for(int i=2;i<num/2;i++)
   {
    if(num%1==0)
    {
     System.out.println("not prime");
     flag=1;
     break;
    }
   }

  if(flag==0)
  {
   System.out.println("prime");
  }


 }

}

No comments:

Post a Comment