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 probably something simple but I can’t find anything.
for(int i=2;i<num;i++){ //primes are allowed to be divided by 1 so we start at 2
if(num % i == 0){ //can be divided by a number other than itself or 1 so we trip out
return false;
} else if(i == num){ //if we've already done checks as high as possible and not tripped out yet then report success
return true;
}
}
i == numwill never occur, since your loop condition isi<num. Try:As pointed out below, the
elsecondition here is redundant, and you only need to check from 2 tosqrt(num)– since the remaining factors have already been checked.There are more improvements that can be made depending on how complex you want to make the problem. Most methods in reality use probabilistic algorithms.