Last active
July 31, 2018 19:40
-
-
Save marvinkome/57b6bc28e42ac39228a75a07457c475e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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