The following code correctly determines if a number is prime:
var num = parseInt(prompt("Number:"));
var ans = "prime";
for (var i = 2; i < num; i++) {
if (num % i === 0) {
ans = "not prime";
break;
}
}
alert(ans);
Why does this code work for an input of "2"?
I thought that an input of 2 would give "not prime", as 2%2===0 would be true.
I thought that an input of 2 would give "not prime", as 2%2===0 would be true.
2 % 2 never happens.
The loop that checks for evenly divisible numbers is:
for (var i = 2; i < num;...
i starts at 2, and num is the user input.
If num is also 2, then the first test of i < num is 2 < 2, which is false. The loop never executes and ans remains "prime".
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