Sunday 11 September 2016

Java Program for Prime number

package My;

import java.util.*;

class PrimeNumbers
{

/*
*
* We have used sqrt method of Math package which find square root
* of a number. To check if an integer(say n) is prime you can check
*  if it is divisible by any integer from 2 to (n-1) or check from 2
*  to sqrt(n), first one is less efficient and will take more time.
*/
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }        
   }
}

No comments:

Post a Comment