Waypoint
Waypoint

Reputation: 17753

C - return after recursion

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

Upvotes: 0

Views: 208

Answers (3)

MoonBun
MoonBun

Reputation: 4402

You probably forgot to write return countPrime(dest); also instead of dest = 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.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612894

Each call to countPrime() get's its own set of local variables. When you assign to dest you are assigning to the copy of dest at the current level of the call stack.

Any algorithm like this is going to need you to pass values back down the call stack. Your fundamental problem is that you are ignoring the value returned from the recursive calls to countPrime().

I've not studied your algorithm in detail, but since you understand the algorithm, you ought to be able to work it out from here.

Upvotes: 4

Erik
Erik

Reputation: 91260

You may want to use return countPrime(dest);

Upvotes: 2

Related Questions