Created
September 7, 2023 22:25
-
-
Save Shariar-Hasan/ad3743848e19557b0e761950b6282e9c to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in 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 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