Created
February 24, 2021 02:47
-
-
Save JayMGurav/e2b2f0e4d343f707cb929fd1cf93b3f3 to your computer and use it in GitHub Desktop.
The sieve of Eratosthenes is an ancient algorithm and is one of the most efficient ways to find all primes up to any given limit.
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
function seive(n){ | |
const arr = Array.from({length: n}, (_,i) => i > 1 ? i : false), | |
limit = Math.sqrt(n); | |
for(let i = 0; i < limit; i++){ | |
let j = i*i; | |
while (j <= n) { | |
arr[j] = false; | |
j = j+i; | |
} | |
} | |
return arr.filter(Boolean); | |
} | |
seive(20) | |
/** | |
* output: [ 2, 3, 5, 7,11, 13, 17, 19 ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment