Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Last active September 22, 2019 06:09
Show Gist options
  • Select an option

  • Save gkucmierz/38323c91c2d2efe03c0dac43c106eda1 to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/38323c91c2d2efe03c0dac43c106eda1 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
const Sieve = (max = 1e5) => {
const maxi = Math.sqrt(max);
const notPrime = new Int8Array(max);
notPrime[0] = notPrime[1] = 1;
for (let i = 2; i < maxi; ++i) {
if (notPrime[i] === 0) {
for (let j = 2*i; j < max; j += i) {
notPrime[j] = 1;
}
}
}
return {
isPrime: n => !notPrime[n],
getPrimes: n => {
const res = [];
let cnt = 0;
for (let i = 0; i <= n; ++i) {
if (!notPrime[i]) {
res[cnt++] = i;
}
}
return res;
}
};
};
const sieve = Sieve(1e5);
sieve.getPrimes(1e3).join` `
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment