Created
March 22, 2016 10:29
-
-
Save chmllr/de778f8171854f29fb56 to your computer and use it in GitHub Desktop.
primes count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} n | |
* @return {number} | |
*/ | |
var countPrimes = function(n) { | |
if (n < 3) return 0; | |
var primes = new Array(n); | |
primes.fill(true, 0, n); | |
for (var i = 4; i < n; i +=2) primes[i] = false; | |
var j = 3; | |
var sqrt = Math.sqrt(n); | |
while (j < sqrt) { | |
var t = j+j; | |
while (t < n) { | |
primes[t] = false; | |
t += j; | |
} | |
j++; | |
while (j < n && !primes[j]) j++; | |
} | |
/* | |
var c = 1; | |
for (var i = 3; i < n; i += 2) c += (primes[i] ? 1 : 0); | |
return c | |
*/ | |
return primes.reduce((acc,e) => acc + (e ? 1: 0), -2); | |
}; | |
var x = new Date(); | |
console.log("result", countPrimes(10000000), "computed in", new Date() - x, "ms") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment