 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Prime numbers upto n - JavaScript
Let’s say, 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];
Example
Following is the code −
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
This will produce the following output in console −
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
Advertisements
 