Skip to content

Instantly share code, notes, and snippets.

@queso
Created October 5, 2017 14:16
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 queso/9500bae047af39ddf10d584fa020bb1e to your computer and use it in GitHub Desktop.
Save queso/9500bae047af39ddf10d584fa020bb1e to your computer and use it in GitHub Desktop.
export default class Sieve {
constructor(endNumber) {
this.endNumber = endNumber;
this.startNumber = 2;
}
range(start, end) {
return Array.from({length: ((end + 1) - start)}, (v, k) => k + start);
}
get primes () {
const set = new Set(this.range(this.startNumber, this.endNumber));
const potentialNonPrimes = Array.from(set).reverse(); // We reverse to start comparing big numbers to small numbers
set.forEach(potentialPrime => {
//console.log(potentialPrime); // This let's you see the iterators it is checking as it goes along.
for (let potentialNonPrime of potentialNonPrimes) {
if((potentialNonPrime != potentialPrime) && (potentialNonPrime % potentialPrime) === 0) {
set.delete(potentialNonPrime);
}
}
});
return Array.from(set); // This runs in about half the time that the other solution did, 9ms instead of the 17-22ms range.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment