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 <= n/2; i++){ if(n % i === 0){ return false; } }; return true; }; const generatePrime = num => { const arr = []; let i = 2; while(arr.length < num){ if(isPrime(i)){ arr.push(i); }; i = i === 2 ? i+1 : i+2; }; return arr; }; console.log("First 6 prime numbers are: "); console.log(generatePrime(6)); console.log("First 16 prime numbers are: "); console.log(generatePrime(16)); 

The output in the console will be ?

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 requires the following output ?

  • 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 < limit; i++) { if (newArray[i]) { arr.push(i); for (let j = i * i; j < limit; j += i) { newArray[j] = false; } } if (arr.length === n) { break; } } return arr.slice(0, n); } console.log(generatePrime(10)); 

The output in the console will be ?

[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ] 
Updated on: 2024-09-30T16:01:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements