Created
April 28, 2012 14:30
-
-
Save bjouhier/2519472 to your computer and use it in GitHub Desktop.
Primes generator
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
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); | |
} | |
} |
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
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