Sum All Primes Challenge- recursive loop

Tell us what’s happening:
I wrote a recursive function for the sum all primes challenge; I’m returning the desired number, but after the return my function keeps running. I’m not sure what I’ve done wrong. Any suggestions to modify the following would be much appreciated. Thanks!

  **Your code so far**

let primeArray = [];

function sumPrimes(num) {
let primeCheck = 0;
if (num === 2) {
  primeArray.push(2)
  console.log(primeArray)
  console.log(`reduce to **${primeArray.reduce((acc, val) => acc + val)}** and return the result`);
  return primeArray.reduce((acc, val) => acc + val);
}
  for (let i = num - 1; i > 1; i--){
    let primeQuery = (num % i === 0)
    //console.log(`${num} divides by ${i} with no remainder: ${primeQuery}`)
    primeCheck = (num % i === 0)? primeCheck + 1 : primeCheck;
    if (primeCheck > 0) {
      console.log(`${num} is not prime`)
      sumPrimes(num - 1)    
  }
  if (i === 2 && primeCheck === 0){
    primeArray.push(num);
    console.log(`${num} is prime!!!`)
    console.log(`Array of primes is now : ${primeArray}`)
    console.log("---------------------")
    sumPrimes(num - 1)
  }
}
}

console.log(sumPrimes(10));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15

Challenge: Sum All Primes

Link to the challenge:

Using a global variable for faux recursion is a big anti pattern.

This is a problem where recursion isn’t a good fit.

What do you mean by ‘keep running’?

1 Like

Thanks Jeremy,

When I console.log the steps, I can see that I reset and continue to loop after returning the reduced result. Do you have a recommendation for handling the array container within the function?

What is the output in the console?

here’s an excerpt…

10 is not prime
9 is not prime
8 is not prime
7 is prime!!!
Array of primes is now : 7

6 is not prime
5 is prime!!!
Array of primes is now : 7,5

4 is not prime
3 is prime!!!
Array of primes is now : 7,5,3

[ 7, 5, 3, 2 ]
reduce to 17 and return the result
6 is not prime
5 is prime!!!
Array of primes is now : 7,5,3,2,5

4 is not prime

Is this when you click ‘Run Tests’? It looks like the function is being run multiple times and the faux recursion is filling up the global variable.


Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

Thanks for that! I can now see that the global variable is mucking this up. Any tips for making that variable local without resetting the array each time the function is called?

You would need to use a default parameter.

But. Again. This is a very bad problem to use recursion on. It is possibly the least efficient approach.

do you know how to test the speed of a solution? I want to compare my recursive answer with the loop one.

function sumPrimes(num) {
  if(num === 2) return 2
  for(let i = 2; i ** 2 <= num; i++) {
    if(num % i === 0) {
      return sumPrimes(num - 1)
    }
  }
  return sumPrimes(num - 1) + num
}

This thread might be interesting to you:

1 Like