From 9fb1d9f49c34a85efac67b2bf02edbec56b69129 Mon Sep 17 00:00:00 2001 From: VitBu <33810987+VitBu@users.noreply.github.com> Date: Sun, 25 Nov 2018 19:53:00 +0200 Subject: [PATCH] Update index.md (#22622) more easy to understand and short than all other solutions --- .../sum-all-primes/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md b/guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md index 0b8a1031c0..864fe82534 100644 --- a/guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md +++ b/guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md @@ -132,6 +132,25 @@ This problem is hard if you have to create your own code to check for primes, so * Functions - Recursion +## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution 2: + + function sumPrimes(num) { + let nums = Array.from({length: num + 1}).map((_, i) => i).slice(2); + for (let n in nums) { + nums = nums.filter(val => val == nums[n] || val % nums[n] != 0); + } + return nums.reduce((prevSum, cur) => prevSum + cur); + } + // test here + sumPrimes(13); + +![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") Run Code + +### Code Explanation: + +* Use `Array.from()` to generate a sequence of numbers up to and including `num`. Combine with `.slice()` to slice off first two indices `[0, 1]` since all prime numbers must be greater than 1. +* If a number is not prime, it is divided by number > 1 other smaller than himself. + ## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: function sumPrimes(num) {