forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path204 Count Primes.js
More file actions
42 lines (34 loc) · 769 Bytes
/
204 Count Primes.js
File metadata and controls
42 lines (34 loc) · 769 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Description:
// Count the number of prime numbers less than a non-negative number, n.
// Leetcode #204
// Language: Javascript
// Problem: https://leetcode.com/problems/count-primes/
// Author: Chihung Yu
/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
if(n <= 2){
return 0;
}
var mem = [];
for(var i = 2; i < n; i++){
mem[i] = true;
}
sq = parseInt(Math.sqrt(n - 1));
for(i = 2; i <= sq; i++){
if(mem[i]){
for(var j = i + i; j < mem.length; j += i){
mem[j] = false;
}
}
}
var count = 0;
for(i = 2; i < mem.length; i++){
if(mem[i]){
count++;
}
}
return count;
}