@jonnin said:
remove the else keyword. and it will work, I think. |
@Ganado said:
The problem is, you are always returning after the very first iteration in isPrime, no matter what. It makes the loop effectively useless. |
You said:
I cant ask him someting which I should had learn 5 months ago......#I blame Call of Duty - Ps3 for that...lol. |
Two people here told you how to fix your isPrime() function. All you did was change
sqrt(nr)
to
nr/2
(which only make the function less efficient, and does not fix the problem) and
1[code] to [code]true
(which does nothing).
Instead of playing Call of Duty, you should read and try to understand the replies you have received. If you don't understand them, then ask more questions.
Let's look at your function with better formatting. I added curly braces to make the logic easier to read. (Note: please use code tags when you post code. Click the Format button that looks like "<>", and paste your code between the tags that are generated.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int isPrime(int nr)
{
int i;
for(i=2;i<=nr/2;i++)
{
if(nr%i==0)
{
return 0;
}
else
{
return true;
}
}
}
|
See that the first time through your for loop, you check to see if nr is divisible by i (2 in the first case). Based on this result you either return 0 or true.
Instead, remove the
else
keyword and move the
return true;
to outside the for loop. (In your code, because you have no {}, simply removing the
else
takes care of this.)
By the way, if you are playing so many video games that you are 5 months behind in a programming class, you have major problems. Programming is something that takes a lot of hands-on time. You might want to go to your teacher and ask for a tutor who can focus directly on you rather than come to an on-line forum to try learn 5 months of c++ in the last few weeks before your class ends.