I\'m having trouble with this C++ code. The integer num
is a number that I want to check if it is prime. However this program is always returning false. It\'s proba
You don't have to check every number, as a lot of them can easily be ruled out. For example, after checking that num
is not divisible by 2
, you can skip all other even numbers. That saves you half the tests.
We also definitely know that any other factor must be less than num/2
(or really sqrt(num)
, but that is harder to compute). That knowledge can save us another half of the tests.
So now we have:
if (num % 2 == 0)
return false;
for(int i = 3; i < num / 2; i += 2){
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
}
}
// arriving here we have found no factors, so it must be a prime
return true;