I have this C code for counting nearest prime-number using this method:
int countPrime(int number) {
int dest=number;
int i;
int p; /*p=0 - not prime number*/
if (dest%2 != 0){
int odm=(int)sqrt(dest);
p=1; //pressume prime number
for(i=3;i<=odm;i++){
if((dest/i)*i == dest){
p=0;
dest=dest++;
countPrime(dest);
}
}
}else{
if (dest == 2){
p=1;
dest=2;
return dest;
}else{
p=0;
dest=dest++;
countPrime(dest);
}
}
return dest;
}
It looks like this method count correctly, but when I use recursion (I call the same method inside that method), I have problems with returns. Apparently, first there is return from recused method, which is then overwritten by the first run of method countPrime. Does anyone knows, how to solve it? That the first run will not be stopped and I get really result form the recursion only?
Thanks
You probably forgot to write
return countPrime(dest);also instead ofdest = dest++;just writedest++;. I compiled your program after this changes and it work very well!I didn’t tried to understand why this works, but when you writing a recursion function each return save in different place so you function will return the correct result and not some in-step result.