Print First N Prime Numbers – Java Code

Objective: Given a number N, write a program to print first N prime numbers.

What is Prime number:??
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A number is either divisible by 1 or by number by itself.

Example:

N = 5
2 3 5 7 11

N = 10
2 3 5 7 11 13 17 19 23 29

Approach:

  • Start from number 2 to till we find N prime numbers
  • Check for each number if it is prime, if yes then increment the prime count.
  • Check this – Check if Given number is Prime
  • Check the code, its self explanatory.

Code:

public class FirstNPrimeNumbers {
static void printPrimeNos(int N){
int number = 2;
int primeCount = 0;
while(primeCount< N){
if(isPrime(number)){
System.out.print(number + " ");
primeCount++;
}
number++;
}
}
static boolean isPrime(int n){
for (int i = 2; i <=Math.sqrt(n) ; i++) {
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
int N = 5;
printPrimeNos(N);
System.out.println();
N = 20;
printPrimeNos(N);
}
}


Output:

2 3 5 7 11
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71