Skip to content

Instantly share code, notes, and snippets.

@supasympa
Last active September 25, 2018 16:32
Show Gist options
  • Save supasympa/d93f01c66262d667e870acdced27f72e to your computer and use it in GitHub Desktop.
Save supasympa/d93f01c66262d667e870acdced27f72e to your computer and use it in GitHub Desktop.
A function to get all prime numbers below a specified value.
function sieve(n){
let arr = new Array(n);
for(let i = 0; i< arr.length; i++){
arr[i] = true;
}
arr[0] = null;
arr[1] = null;
function setToFalseEvery(n){
return arr.forEach((item, i, arr) => {
if(i < 2 || i % n !== 0){
return arr[i] = item;
}
return arr[i] = false;
});
}
function findFirstTrueItemIndex(){
return arr.findIndex(item => item === true);
}
const squareRootOfN = Math.round(Math.sqrt(n));
const arr2 = [];
let i2;
for(let i=2; i <= squareRootOfN; i++){
i2 = findFirstTrueItemIndex();
arr2.push(i2);
setToFalseEvery(i2);
}
arr = arr.reduce((acc, item, i) => {
if(item === true){
acc.push(i);
}
return acc;
}, []);
return [...arr2, ...arr];
}
console.log(sieve(999999).toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment