Sum All Primes recursive function

I tried solving this problem using recursion and I dont understand one thing about recursions…

To callback on the function checkPrime(), how come I need to add return?

How come the function doesn’t call back on itself without the return?

The function sumPrimes() already has a return checkPrime() to call the function and the function checkPrime() has a return sum that should end the function with the sum.

Why does checkPrime(num-1) need a return in the front?

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function sumPrimes(num) {
var sum = 0;

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

return checkPrime(num)
}

sumPrimes(10);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36

Challenge: Sum All Primes

Link to the challenge:

I don’t this that this code does what yu think that it does. You aren’t really checking primality.

Can you please explain? The code passes all tests

Ohhhh… Your CheckPrime is just a faux recursion sumPrimes function.

The name choice is confusing.

function sumPrimes(num) {
  let sum = 0;

  function recursiveCheat(num) {
    if (num<=1) {
      return sum;
    }
    // This is the only part that checks for primality
    for (let i=2; i<num; i++) {
      if (num % i === 0) {
        return recursiveCheat(num-1);
      }
    }
    sum += num
    return recursiveCheat(num-1);
  }

  return recursiveCheat(num);
}

sumPrimes(10);

But this is really a confusingly written while loop

function sumPrimes(num) {
  let sum = 0;

  while (num > 1) {
    // This is the only part that checks for primality
    let isPrime = true;
    for (let i=2; i<num; i++) {
      if (num % i === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime)
      sum += num
    num--;
  }

  return sum;
}

sumPrimes(10);
2 Likes

On the why you need return, if you don’t have return inside a function it returns undefined

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.