Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Listing all the prime numbers upto a specific number in JavaScript
We are required to write a JavaScript function that takes in a number, say n, and returns an array containing all the prime numbers upto n.
For example: If the number n is 24.
Then the output should be −
const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const num = 24;
const isPrime = num => {
let count = 2;
while(count < (num / 2)+1){
if(num % count !== 0){
count++;
continue;
};
return false;
};
return true;
};
const primeUpto = num => {
if(num < 2){
return [];
};
const res = [2];
for(let i = 3; i <= num; i++){
if(!isPrime(i)){
continue;
};
res.push(i);
};
return res;
};
console.log(primeUpto(num));
Output
The output in the console will be −
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
Advertisements
