Sum all primes returns correct sums but doesn't pass test

Sum all primes returns correct sums but doesn't pass test
0

#1

Hello. I have scanned the forum for “sum all primes” and have seen similar questions but I couldn’t solve my problem from those. If the answer is out there, the algorithm’s title is not in the title of the topic. Soz.

What I have is a code that returns a sum that I see in the test section. That would make me think that it works. I have also tried others:
sumPrime(2) returns 2
sumPrime(5) returns 10 …

Help me, Codie Won. You’re my only hope.

function isPrime(val) {
    for(var i = 2; i < val; i++) {
        if(val % i === 0) {
            return false;//is composite and not in the cool prime club
        }
    }
    return val > 1; //start at whole numb two
}

var primes=[];//arr to push to

function sumPrimes(num) {
 for (var n = 2; n <= num; n++){//from two to num
   if(isPrime(n)){//if passes test in f(x) above, ...
     primes.push(n);
   } 
 } var sum = primes.reduce(function(a,b){
   return a+b;
 }, 0);//standard reduce
  return sum;
}

sumPrimes(977);//returns 73156 but i don't pass the test and sumPrimes(10) returns 17.

Sum All Primes - 7/17/2018
#2

Move the primes variable inside the function that uses it. Solutions with global variables are not accepted in the challenges.


#3

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your code relies on primes being an empty array when the function is called, but after sumPrimes has been executed it is no longer an empty array. This means that your function will only work once.


#4

Thank you! I have copied and pasted your detailed explanation for my notes. While I have read about the problem with global variables before, until I used one and had it mess with me, it didn’t stick. I see exactly what you’re saying. Thank you. Now go have a cookie!


#5

It’s hard to wrap your head around the significance of some things until you waste a couple hours getting burned by them.
:cookie: