Java Program to Display First N Prime Numbers

Prime number

Java program to display first n prime numbers has been shown here. Here n is a positive integer. For example if n = 5, we get first 5 prime numbers i.e. 2, 3, 5, 7, 11.



Page contents:

1. Program & Output




1. Java Program & output to display first N prime numbers

Code has been copied
/*********************************************
	     alphabetacoder.com
Java program to display first N prime numbers
**********************************************/

import java.util.Scanner;
import java.lang.*;

class Main {
    // function to check prime
    boolean check_prime(int num) {
        // declare variables
        int i;
        // 1 is not prime
        if (num == 1)
            return false;
        // check divisibility of num
        for (i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false; // num is composite so return false
            }
        }
        // num is prime so return true
        return true;
    }

    public static void main(String[] args) {
        // declare instance of Scanner class
        Scanner sc = new Scanner(System.in);
        // declare object of class
        Main obj = new Main();
        // declare variables
        int n, num, count;

        // take input of the number
        System.out.print("Enter the no. of primes = ");
        n = sc.nextInt();

        // initialize
        num = 1;
        count = 0;

        System.out.print("First " + n + " primes: ");
        // find n number of primes
        while (count < n) {
            // check if current number is prime
            if (obj.check_prime(num)) {
                System.out.print(" " + num);
                count++; // increment counter
            }
            num++; // increment number
        }
    }
}

Output


Case 1:

Enter the no. of primes = 3

First 3 primes: 2 3 5


Case 2:

Enter the no. of primes = 9

First 9 primes: 2 3 5 7 11 13 17 19 23