
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Array of First N Prime Numbers in JavaScript
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 ]
Advertisements