Skip to content

Instantly share code, notes, and snippets.

@JayMGurav
Created February 24, 2021 02:47
Show Gist options
  • Save JayMGurav/e2b2f0e4d343f707cb929fd1cf93b3f3 to your computer and use it in GitHub Desktop.
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.
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