# I am finding it difficult understanding the solution to this prime number question

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

Ans.

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

function sumPrimes(num) {
// Helper function to check primality
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
//this is the confusion, if num = 10, wont num % 2 == 0, hence the prime 2
//becomes false
if (num % i == 0)
return false;
}
return true;
}

// Check all numbers for primality
let sum = 0;
for (let i = 2; i <= num; i++) {
if (isPrime(i))
sum += i;
}
return sum;
}

sumPrimes(10);
``````

Hello there.

Do you have a question?

Learning to describe problems is hard, but it 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.

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, I have edited the post and included the question.

Canâ€™t wrap my mind about the confusion.
if num equals 10, then num % 2 equals 0 and hence 10 is not a prime.

1 Like

Is it not the â€śiâ€ť we are trying to find if its a prime number or not?

This function would be called like this: `isPrime(5)` or `isPrime(20)`. What would you expect a function with that name to do?

for instance, if(20%2) will give a reminder of 0, hence return false - but 2 is a prime number which is supposed to return true.

Back up. Look at the function name. `isPrime(num)` checks if `num` is prime.

1 Like

Thank you, Iâ€™ve got it now.

1 Like

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