Created
October 5, 2017 14:16
-
-
Save queso/9500bae047af39ddf10d584fa020bb1e to your computer and use it in GitHub Desktop.
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
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