1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
bool isPrime(int number)
{
int counter = 2;
while(counter<number)
{
if (number%counter==0)
return false;
else
return true;
}
return 0;
}
|
First of all, get rid of the 'return 0'.
The problem with the above code is that you are only dividing 'number' by 2, and then returning true immediately if it doesn't leave a remainder of 0.
So in summary, there are 2 problems:
(1) We learned that to check if a number is prime, we need to see if it can be divided by ANY number from 0 to 'number'-1. Here, you are only dividing 'number' by 2. You need to increment 'counter' in the loop, so it then checks divisibility by 3, then 4, then 5... and so on.
(2) We learned that we return true outside the while-loop, as that is where we know for sure that the number is prime. You, on the other hand, are potentially returning true as soon as the division by 2 doesn't work.
Check it out. Lets say I pass the number 15 to the isPrime function (spoiler, 15 is not prime!). It should return false, but your function returns true. Why? Because 15 divided by 2 will NOT give a remainder of 0, hence the 'else' clause will be executed, returning true.
The logic here is wrong because we need to check EVERY division from 2 to 14 (i.e. all of them must have a remainder other than 0) before we know for sure that its prime. This is why we return true outside the loop.
So in summary, return false inside loop as soon as remainder is 0. If remainder is not 0, do NOT return true, because we may still have more factors to check. Return true only when we get out of the loop (which is when counter == number), i.e. when all numbers from 2 to 'number'-1 have been checked.
So how will you fix these 2 problems?