Created
February 11, 2013 20:49
-
-
Save raiden-dev/4757492 to your computer and use it in GitHub Desktop.
Prime numbers generator with simple caching
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
/** | |
* Prime numbers generator | |
* @constructor | |
*/ | |
function Prime() { | |
this.primes = [1]; | |
} | |
/** | |
* Test for primality | |
* @method isPrime | |
* @param {Number} num | |
*/ | |
Prime.prototype.isPrime = function(num) { | |
if (num !== 2) { | |
if (num % 2 === 0) { | |
return false; | |
} | |
else { | |
for (x=3; x<=Math.sqrt(num); x+=2) { | |
if (num % x === 0) { | |
return false; | |
} | |
} | |
} | |
} | |
return true; | |
} | |
/** | |
* Get next prime number | |
* @method getNext | |
*/ | |
Prime.prototype.getNext = function() { | |
var current = this.primes[this.primes.length-1]; | |
current++; | |
while (!this.isPrime(current)) current++; | |
this.primes.push(current); | |
return current; | |
} | |
/** | |
* Get some prime numbers | |
* @method getSome | |
* @param {Number} qty Quantity | |
* @param {Number} [from] Start position | |
*/ | |
Prime.prototype.getSome = function(qty, from) { | |
from = from || this.primes.length; | |
for (var i=0; i<qty; i++) { | |
if (!this.primes[from+i]) { | |
this.getNext(); | |
} | |
} | |
return this.primes.slice(from, from+qty); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment