LeetCode: Count Primes Solution

1/**
2 * @param {number} n
3 * @return {number}
4 */
5var countPrimes = function (n) {
6 return sieveOfEratosthenes(n).filter(Boolean).length
7}
8
9const sieveOfEratosthenes = n => {
10 const prime = new Uint8Array(n).fill(true)
11 prime[0] = prime[1] = false
12 for (let i = 2; i * i <= n; i++) {
13 if (prime[i]) {
14 for (let k = i * i; k <= n; k += i) {
15 prime[k] = false
16 }
17 }
18 }
19 return prime
20}

Comments

Loading comments...

Tags

leetcode

math

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Maximum Points You Can Obtain From Cards

May 11, 2021

Previous Post

HoningJS

Search Posts