Skip to content

Instantly share code, notes, and snippets.

@marvinkome
Last active July 31, 2018 19:40
Show Gist options
  • Select an option

  • Save marvinkome/57b6bc28e42ac39228a75a07457c475e to your computer and use it in GitHub Desktop.

Select an option

Save marvinkome/57b6bc28e42ac39228a75a07457c475e to your computer and use it in GitHub Desktop.
function addUpPrimes(n) {
// using the seive of Eratosthenes get all primes
const list = [];
for (let i = 2; i <= n; i++) {
list[i] = { index: i, value: true };
}
// our limit
const limit = Math.sqrt(n);
//run over the list, starting at 2
for (let i = 2; i <= 10; i++) {
for (let x = i + i; x <= n; x += i) {
// set all multiples of i to false
list[x] = false;
}
}
// using reduce, filter out all false values and return a new array with the number
const newList = list.reduce((acc, curr) => {
if (curr !== false) {
acc.push(curr.index);
}
return acc;
}, []);
// add up primes
return newList.reduce((prev, curr) => prev + curr);
}
console.log(addUpPrimes(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment