Java – List the Starting N Prime Numbers
Write a Java program to list first N prime numbers. Where N is a number input by the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.util.Scanner; public class NPrimeNumbers { private static Scanner scanner = new Scanner( System.in ); public static void main(String[] args) { System.out.println("Enter total required prime numbers: "); String input = scanner.nextLine(); int totalNumber = Integer.parseInt( input ); int count = 0; System.out.println("A List of the first " + totalNumber + " prime numbers"); for (int num = 2; count < totalNumber; num++) { boolean isPrime = true; for (int i=2; i <= num/2; i++) { if ( num % i == 0) { isPrime = false; break; } } if ( isPrime == true ) { System.out.println(num); count++; } } } } |
Compile and run the program
javac NPrimeNumbers.java java NPrimeNumbers
Output:
Enter total required prime numbers: 5 A List of the first 5 prime numbers 2 3 5 7 11