Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this prime-checker work?

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.

like image 392
Zamt3x Avatar asked Aug 14 '26 05:08

Zamt3x


1 Answers

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".

like image 161
meagar Avatar answered Aug 16 '26 17:08

meagar