Skip to content

Instantly share code, notes, and snippets.

@pldespaigne
Last active August 30, 2019 11:05
Show Gist options
  • Save pldespaigne/ad48b03cd06bf1efe670c4f3bf238859 to your computer and use it in GitHub Desktop.
Save pldespaigne/ad48b03cd06bf1efe670c4f3bf238859 to your computer and use it in GitHub Desktop.
Js implementation of the Sieve of Atkin to find the n first prime number (https://en.wikipedia.org/wiki/Sieve_of_Atkin)
function atkin(MAX) {
const SQRT_MAX = Math.floor(Math.sqrt(MAX) + 1);
const array = new Array(MAX).fill(false);
for (let x = 1; x < SQRT_MAX; x++) {
for (let y = 1; y < SQRT_MAX; y++) {
let k = 4 * x * x + y * y;
if ((k < MAX) && ((k % 12 === 1) || (k % 12 === 5))) {
array[k] = !array[k];
}
k = 3 * x * x + y * y;
if ((k < MAX) && (k % 12 === 7)) {
array[k] = !array[k];
}
if (x > y) {
k = 3 * x * x - y * y;
if ((k < MAX) && (k % 12 === 11)) {
array[k] = !array[k];
}
}
}
}
array[2] = true;
array[3] = true;
for (let n = 5; n <= SQRT_MAX; n++) {
if (array[n]) {
let n2 = n * n;
for (let k = n2; k < MAX; k += n2) {
array[k] = false;
}
}
}
let res = []
for(let i = 0 ; i < array.length ; i++) {
if(array[i])res.push(i);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment