Hello,
I’m trying to understand one of the solutions to the - “Sum all prime numbers” challenge.
Can someone explain to me how 9 which is not a prime number will not pass the conditons underneath? it is odd so will not return false for the first part and is not equal to 0 or 1.
//function to check if a number is prime or not
function isPrime(x) {
for (let i = 2; i < x; i++) {
if (x % i === 0) return false;
}
return x !== 1 && x !== 0;
}
There is a loop in there
for (let i = 2; i < x; i++) {
if (x % i === 0) return false;
}
In side of this loop, you check if x % 2 === 0
, x % 3 === 0
, …, x % (x - 1) === 0
.
–
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 (’).
1 Like
Thanks for the reply, and i’ll be sure to do this for future posts.
So when x = 9 and i = 3 this means x % i === 0 this returns false?