- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 ]
- Related Articles
- Counting prime numbers from 2 upto the number n JavaScript
- Listing all the prime numbers upto a specific number in JavaScript
- The numbers 13 and 31 are prime numbers. Both these numbers have same digits 1 and 3. Find such pairs of prime numbers upto 100 .
- Counting the number of 1s upto n in JavaScript
- Sum all perfect cube values upto n using JavaScript
- JavaScript function to take a number n and generate an array with first n prime numbers
- Sum of the first N Prime numbers
- Finding all possible prime pairs that sum upto input number using JavaScript
- Print the nearest prime number formed by adding prime numbers to N
- Checking for co-prime numbers - JavaScript
- Prime numbers in a range - JavaScript
- Count numbers upto N which are both perfect square and perfect cube in C++
- How to generate Prime Numbers in JavaScript?
- Sum of all prime numbers in JavaScript
- Prime numbers within a range in JavaScript

Advertisements