# Counting prime numbers from 2 upto the number n JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
Published on 23-Nov-2020 11:37:49