
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
Prime Numbers Upto N in 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