JavaScript function to take a number n and generate an array with first n prime numbers

We are required to write a JavaScript function that takes in a number n and returns an array that contains first n prime numbers. We know that prime numbers are those numbers that are only divisible by 1 and themselves like 2, 3, 19, 37, 73 etc.

Let's understand the problem with an example ?

Input: n = 6; 
Output: prime_numbers = [ 2, 3, 5, 7, 11, 13 ]

Using Iteration

We will first write a function that checks whether a given number is prime or not and then run a loop till the given number n to generate n prime numbers.

Example

The JavaScript program to generate first prime numbers is ?

const isPrime = (n) => {
   for(let i = 2; i  {
   const arr = [];
   let i = 2;
   while(arr.length 

First 6 prime numbers are: 
[ 2, 3, 5, 7, 11, 13 ]
First 16 prime numbers are: 
[
   2,  3,  5,  7, 11, 13,
  17, 19, 23, 29, 31, 37,
  41, 43, 47, 53
]

Using Sieve of Eratosthenes Algorithm

This algorithm is more efficient for generating multiple prime numbers. It follows these steps:

  • Initialize a boolean array of size 10000 with TRUE values.
  • Then, iterate through each number starting from 2.
  • If a number is still marked as TRUE, add it to the array of primes, and all its multiples are marked as FALSE in boolean array.
  • Continue this process until the array of primes contains n prime numbers.

Example

Let's see the practical implementation ?

function generatePrime(n) {
   const limit = 10000; 
   const arr = [];
   const newArray = new Array(limit).fill(true);
   
   for (let i = 2; i 

First 10 prime numbers using Sieve:
[
   2,  3,  5,  7, 11,
  13, 17, 19, 23, 29
]

Comparison

Method Time Complexity Best For
Iteration O(n * sqrt(m)) Small values of n
Sieve of Eratosthenes O(n log log n) Large values of n

Conclusion

The iterative approach is simpler but slower for large inputs. The Sieve of Eratosthenes is more efficient for generating multiple prime numbers, especially when n is large.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements