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

function sumPrimes(num) {

  function isPrime(num) {

    for (let i = 2; i <= Math.sqrt(num); i++) {

      if (num % i == 0) {

        return false;

      }

    }

    return true;

  }

  let sum = 0;

  for (let i = 2; i <= num; i++) {

    if (isPrime(i)) {

      sum += i;

    }

  }

  return sum;

}

console.log(sumPrimes(4));
// 2, 3, 5, 7, 11, 13, 17.........

/*
Explanation :- 

sp(4)

sum = 0

for i = 2 <= 4 true

if ip(2) --> now check in function

for i = 2 <= 1.414 false, return true

sum = 0 + 2, i++ in sp(num)

for i = 3 <= 4 true

if ip(3) --> check in function

for i = 2 <= 1.732 false, return true

sum = 2 + 3, i++ in sp(num)

for i = 4 <= 4 true

if ip(4) --> check in function

for i = 2 <= 2 true

if 4 % 2 == 0 true, return false, i++ in sp(num)

for i = 5 <= 4 false, return sum = 5 */

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Hello there.

Do you have a question?

If so, please edit your post to include it.

Learning to describe problems is an important part of learning how to code.

Also, the more information you give us, the more likely we are to be able to help.

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