I've been trying to pass a challenge for so long, and despite reading up multiple solutions and advice online I can't seem to apply it correctly.
The instructions are "Define a function isPrime that takes one integer argument and returns true or false depending on if the integer is a prime."
I've tried a lot of things but this is the furthest I've been able to get:
function isPrime(num) {
if (num <= 1) return false;
if (num === 2) return true;
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
else return true;
}
But then I'm told: "9 is not a prime number."
Any help would be appreciated and thanks!
You should avoid the else case and return only after for loop completion. Although for loop count can be reduced by updating condition to i <= Math.sqrt(num)
( as @PatrickRoberts suggested ).
function isPrime(num) {
if (num <= 1) return false;
if (num === 2) return true;
// storing the calculated value would be much
// better than calculating in each iteration
var sqrt = Math.sqrt(num);
for (var i = 2; i <= sqrt; i++)
if (num % i === 0) return false;
return true;
}
FYI : In your code on the first iteration of the loop num % i === 0
(9 % 2
) would be false
and it would return the else statement(true
).
The problem is with the else return true;
in your for loop.
At the first iteration, where i
is 2, just after you checked that 9 % i
wasn't 0, you execute the else
block and return true
.
You shouldn't return true
before all the iterations failed to return false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With