Skip to content

Instantly share code, notes, and snippets.

@nickleefly
Forked from trevnorris/prime-generator.js
Last active January 12, 2016 09:56
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 nickleefly/2a815a25da8f3646ad48 to your computer and use it in GitHub Desktop.
Save nickleefly/2a815a25da8f3646ad48 to your computer and use it in GitHub Desktop.
fastest js prime generator been able to get http://jsperf.com/123123123456
// Thanks to @isntitvacant (https://github.com/chrisdickinson) for optimizing the
// bit shift performance tweaks.
var SB = require('buffer').SlowBuffer;
var ITER = 2e4;
var SIZE = 1e3;
function genPrimes(max) {
var primes = new Array();
var len = (max >>> 3) + 1;
var sieve = new SB(len);
var cntr = 0;
var x = 2;
var j;
sieve.fill(0xff, 0, len);
for (cntr = 0, x = 2; x <= max; ++x) {
if (sieve[x >>> 3] & (1 << (x & 7))) {
primes[cntr++] = x
for(j = 2 * x; j <= max; j += x)
sieve[j >>> 3] &= ~(1 << (j & 7))
}
}
return primes;
}
var t = process.hrtime();
for (var i = 0; i < ITER; i++)
genPrimes(SIZE);
t = process.hrtime(t);
console.log(((t[0] * 1e6 + t[1] / 1e3) / ITER).toFixed(1) + ' us/op');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment