You are here

Java program to print prime numbers

Java program to print prime numbers, a user input how many of them are required. Remember, the smallest prime number is 2. We use the sqrt method of Math package, which finds the square root of a number. To check if an integer (say n) is prime, you can check if it's divisible by any integer from 2 to (n-1) or check from 2 to sqrt(n), the first one is less efficient and takes more time.

Print prime numbers in Java

import java.util.*;

class PrimeNumbers
{
  public static void main(String args[])
  {
    int n, status = 1, x = 3, count, j;

    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 (count = 2; count <=n; )
    {
      for (j = 2; j <= Math.sqrt(x); j++)
      {
        if (x%j == 0)
        {
          status = 0;
          break;
        }
      }
      if (status != 0)
      {
        System.out.println(x);
        count++;
      }
      status = 1;
      x++;
    }
  }
}

Output of program:
Java program to prime numbers output

Download Prime numbers program class file.

Share this