Suppose n is 21. Then look what happens in the loop:
1 2 3 4 5 6 7 8
|
while ( i <= sqrt(n))
{
if ( n % i == 0) {
is_prime = false;
break;
}
i++;
}
|
Now sqrt(n) is 4.58. Starting with i=2, since 2 < 4.58 we enter the loop.
Then n%i is (21 mod 2) which is 1 (the remainder of 21/2), Since that is not zero we skip the body of the if, then increment I, which becomes 3.
Now 3 < 4.58, so we again enter the loop body and calculate 21%3 which IS zero, so we enter the if, set is_prime to false and break out of the loop, having found the answer (21 is not prime.
Now suppose n=17. Let's do the same thing.
The sqrt of 17 is 4.123. Starting with i = 2, since 2 < 4.123 we enter the loop and compute 17%2 which is 1 so we skip the body of the if-statement and increment i to be 3 and repeat the loop check. Since 3 < 4.123 we check 17%3, which is 2.
Since that is not zero, we again skip the body of the if-statement and increment i again, to become , and repeat the loop check. Since 4 < 4.123 we enter the loop body and check 17%4, which is 1. Since that is not zero, we again skip the body of the if-statement and increment i, which becomes 5.
We again perform the loop check. Since 5 is not <= 4.123, the loop terminates, having never set is_prime to false, so it is still true - our answer: 17 is a prime.