Wednesday, July 22, 2020

Sum All Primes

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes

Intermediate Algorithm Scripting: Sum All Primes


A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.

Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.

sumPrimes(10) should return a number.

sumPrimes(10) should return 17.

sumPrimes(977) should return 73156.


function* primesGenerator(qualifierFunc) {
    const primes = [2];
    yield primes[0];
    for (let odd = 3; ; odd += 2) {
        if (qualifierFunc && !qualifierFunc(odd)) {
            return;
        }
 
        if (primes.some(n => odd % n === 0)) {
            continue;
        }

        yield odd;
        primes.push(odd);
    }
}


function sumPrimes(num) {
    return Array.from(primesGenerator(n => n <= num)).reduce((a, b) => a + b);
}

console.log(sumPrimes(10));
console.log(sumPrimes(977));


Output:
17
73156

No comments:

Post a Comment