Skip to content

Instantly share code, notes, and snippets.

@Shariar-Hasan
Created September 7, 2023 22:25
Show Gist options
  • Save Shariar-Hasan/ad3743848e19557b0e761950b6282e9c to your computer and use it in GitHub Desktop.
Save Shariar-Hasan/ad3743848e19557b0e761950b6282e9c to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Javascript
const numberNeeded = 20;
let isPrime = new Array(numberNeeded + 1).fill(true);
isPrime[0] = false; // setting 0 as not prime
isPrime[1] = false; // setting 1 as not prime
function sieve(n) {
let j = 2;
while (j * j <= n) {
if (isPrime[j]) {
for (let i = j * j; i <= n; i += j) {
isPrime[i] = false;
}
}
j++;
}
}
sieve(numberNeeded);
console.log(isPrime);
// Output :
// [
// false, false, true, true,
// false, true, false, true,
// false, false, false, true,
// false, true, false, false,
// false, true, false, true,
// false
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment