Skip to content

Instantly share code, notes, and snippets.

@bjouhier
Created April 28, 2012 14:30
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 bjouhier/2519472 to your computer and use it in GitHub Desktop.
Save bjouhier/2519472 to your computer and use it in GitHub Desktop.
Primes generator
exports.generator = function() {
var found = [];
function isPrime(p) {
for (var i = 0; i < found.length; i++) {
var q = found[i];
if (p % q === 0) return false;
if (q * q > p) return true;
}
return true;
}
return function(cb) {
var p;
if (found.length === 0) {
p = 2;
} else {
p = found[found.length - 1] + 1;
while (!isPrime(p)) p++;
}
found.push(p);
cb(null, p);
}
}
var nextPrime = require('./primes').generator();
for (var i = 0; i < 20; i++) console.log(nextPrime(_));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment