Skip to content

Commit 4df5482

Browse files
author
chenzhao
committed
feat(0204): Count Primes
1 parent 96eb5fd commit 4df5482

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

0204. Count Primes.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Count the number of prime numbers less than a non-negative number, n.
2+
3+
// Example:
4+
5+
// Input: 10
6+
// Output: 4
7+
8+
// Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
9+
10+
/**
11+
* @param {number} n
12+
* @return {number}
13+
*/
14+
const countPrimes = function(n) {
15+
const notPrimes = Array(n).fill(false)
16+
let res = 0
17+
for (let i = 2; i < n; i++) {
18+
if (notPrimes[i] === false) {
19+
res++
20+
}
21+
for (let j = 2; i * j < n; j++) {
22+
notPrimes[i * j] = true
23+
}
24+
}
25+
return res
26+
}

0 commit comments

Comments
 (0)