Display First "n" Prime Numbers | Java Programs

Output:

*** First 'n' Prime Numbers ***

Enter the value of n: 8
First 8 prime numbers are:
2
3
5
7
11
13
17
19

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

class FirstNPrimeNumbers {

    public static void main(String args[]) {
        int n;
        int status = 1;
        int num = 3;
        Scanner scanner = new Scanner(System.in);
        System.out.println("*** First 'n' Prime Numbers ***" + "\n");
        System.out.print("Enter the value of n: ");
        n = scanner.nextInt();
        if (n >= 1) {
            System.out.println("First " + n + " prime numbers are:");
            System.out.println(2);
        }

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

Related Post



sentiment_satisfied Emoticon