Created
August 23, 2020 14:39
-
-
Save FeezyHendrix/c6b8d0decbd40388c6b97dc4f99c2a06 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes - Javascript
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
const sieveofetathothese = (n) => { | |
// Create a boolean array that holds true for all the range of n | |
let prime = []; | |
// initialize the first non-prime number which is 2 | |
let p = 2; | |
// populate array with the boolean of true | |
for (let i = 0; i <= n; i++) prime.push(true); | |
// While the multiples of the current value of p is not more than the number n | |
while(p * p <= n) { | |
// If the current item of p is still true; | |
if(prime[p] === true) { | |
// For all multiples of the item swap it to false | |
// If p = 2; thus p * p is 4 | |
// i = 4; if n = 10 | |
for (let i = p * p; i <= n; i += p) { | |
// make prime[4] since i is currently 4 then increment it with the value of p | |
prime[i] = false; | |
// since value of p is 2 then i increases to i+p = 6 (4 + 2); | |
// thus falsilfies all multiples of p that is less than n | |
} | |
} | |
// increment p Eg is p = 2; increment to 3 | |
p++; | |
} | |
for(let k = 2; k <= n; k++) { | |
// log all true items in the booleen array | |
if(prime[k]) console.log(k) | |
} | |
} | |
sieveofetathothese(10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment