Count Primes
title: Find Primes subtitle: Sieve of Eratosthenes tags: [“solution”]
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Pseudo
Following is the algorithm to find all the prime numbers less than or equal to a given integer n by Eratosthenes’ method:
Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). Initially, let p equal 2, the first prime number. Starting from p2, count up in increments of p and mark each of these numbers greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc.. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
Solution
var countPrimes = function (number) {
const numbers = new Array(number + 1);
numbers.fill(true);
numbers[0] = numbers[1] = false;
let i = 2
while (i <= Math.sqrt(number)) {
for (let j = 2; i * j <= number; j++) numbers[i * j] = false;
i++
}
return numbers.reduce(
(primes, isPrime, prime) => (isPrime ? primes.concat(prime) : primes),
[]
).length
}
comments powered by Disqus