Q:

program logic of printing the prime numbers

Can any body help to understand this java program?
It just prints prime numbers, as you enter how many you want and it works well.
class PrimeNumbers
{      
     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++;
      }         
   }
}

I don't understand this for loop condition
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )

why we are taking sqrt of num...which is 3....why we assumed it as 3?

A:

Imagine that n can be divided by a number k that is greater than sqrt(n). Then you have:
n = k * j

where j is a number which must be less than sqrt(n) (if both k and j are greater than sqrt(n) then their product would be greater than n).
So you only need to find the divisors that are less than or equals to sqrt(n) and you can find those that are greater than or equals to sqrt(n) by a simple division. In my example, once you have found j, you can find k = n / j.

