

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Counting prime numbers from 2 upto the number n JavaScript
We are required to write a JavaScript function that takes in a number, say n, as the first and the only argument.
The function should then return the count of all the prime numbers from 2 upto the number n.
For example −
For n = 10, the output should be: 4 (2, 3, 5, 7) For n = 1, the output should be: 0
Example
const countPrimesUpto = (num = 1) => { if (num < 3) { return 0; }; let arr = new Array(num).fill(1); for (let i = 2; i * i < num; i++) { if (!arr[i]) { continue; }; for (let j = i * i; j < num; j += i) { arr[j] = 0; }; }; return arr.reduce( (a,b) => b + a) - 2; }; console.log(countPrimesUpto(35)); console.log(countPrimesUpto(6)); console.log(countPrimesUpto(10));
Output
And the output in the console will be −
11 3 4
- Related Questions & Answers
- Prime numbers upto n - JavaScript
- Counting the number of 1s upto n in JavaScript
- Listing all the prime numbers upto a specific number in JavaScript
- Print the nearest prime number formed by adding prime numbers to N
- Counting number of 9s encountered while counting up to n in JavaScript
- Find Sum of Series 1^2 - 2^2 + 3^2 - 4^2 ... upto n terms in C++
- Finding all possible prime pairs that sum upto input number using JavaScript
- Sum of the first N Prime numbers
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Counting n digit Numbers with all unique digits in JavaScript
- JavaScript function to take a number n and generate an array with first n prime numbers
- Print prime numbers from 1 to N in reverse order
- Counting How Many Numbers Are Smaller Than the Current Number in JavaScript
- Counting largest numbers in row and column in 2-D array in JavaScript
- Sum of the series 1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + upto n terms in C++
Advertisements