Well lets look at it line by line.
line 1) we check if the number is greater than 2, if so it could possibly be a prime. If it's less than it won't be since there are none (besides 2 that we checked earlier).
line 3) this pretty much says if the number is even the it is not possibly a prime. You could write it like this
bool isPrime = prime % 2;
It pretty much checks if the first bit is set which would be the 1 bit.
line 4) it sets i equal to 3 since we already checked if it was divisible by 2. We know its not even so there is no need to check if it's divisible by any even numbers that is why we increment by 2 instead of 1 at the end of the condition you could also write it as
i = i + 2
the center condition means if it could possibly be a prime then to search. The next part of the condition checks if i is less than or equal to the sqrt of the number. If you think about it the sqrt of 100 is 10. So the largest number to check would be 10 since 10 x 10 == 100 you will have already checked the rest. You could have written this as
sqrt(i) <= prime
the reason we have to check until the sqrt is because what if there is a number like 121 where it is made by 2 primes multiplied (11 x 11).
line 6) we just assign if it is divisible or not, if it is divisible it is not prime, if it is not divisible it is possibly a prime.
line 9) this is a ternary operator it would be the same as something like
1 2 3 4 5 6 7 8 9
|
if(isPrime)
{
std::cout << "prime.";
}
else
{
std::cout << "nor prime.";
}
std::cout << std::endl;
|