Skip to content

Instantly share code, notes, and snippets.

@chmllr
Created March 22, 2016 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmllr/de778f8171854f29fb56 to your computer and use it in GitHub Desktop.
Save chmllr/de778f8171854f29fb56 to your computer and use it in GitHub Desktop.
primes count
/**
* @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