You are here

Java program print prime numbers

Java program to print prime numbers, number of prime numbers required is asked from a user. Remember the smallest prime number is 2. We are using 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), the first one is less efficient and will take more time.

Java programming code

  1. import java.util.*;
  2.  
  3. class PrimeNumbers
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int n, status = 1, num = 3, count, j;
  8.  
  9.       Scanner in = new Scanner(System.in);
  10.       System.out.println("Enter the number of prime numbers you want");
  11.       n = in.nextInt();
  12.      
  13.       if (n >= 1)
  14.       {
  15.          System.out.println("First "+n+" prime numbers are:");
  16.          System.out.println(2);
  17.       }
  18.      
  19.       for (count = 2; count <=n;)
  20.       {
  21.          for (j = 2; j <= Math.sqrt(num); j++)
  22.          {
  23.             if (num%j == 0)
  24.             {
  25.                status = 0;
  26.                break;
  27.             }
  28.          }
  29.          if (status != 0)
  30.          {
  31.             System.out.println(num);
  32.             count++;
  33.          }
  34.          status = 1;
  35.          num++;
  36.       }        
  37.    }
  38. }

Output of program:
Java program to prime numbers output

Download Prime numbers program class file.