Search code examples
c++recursiongreatest-common-divisor

How are values returned back when the base case is reached


I was learning some basic algorithms then I came across Euclidean Algorithm to find GCD of two numbers.

I understood that Algorithm on paper. There is a iterative code to do the same

int euclid_gcd(int a, int b){
    int dividend = a>=b ? a : b;
    int divisor = a<=b ? a : b;
    while(divisor!=0){
        int remainder = dividend % divisor;
        dividend = divisor;
        divisor = remainder;
        }
    return dividend; 
}

I am very comfortable with the above iterative code Then there were two more recursive versions of the same code

int gcd(int a, int b){
    if(a==b) 
        return a;
    if(a>b) 
        return gcd(a-b,b);
    return gcd(a,b-a);
}

And this is the smallest one in terms of lines]

int gcd(int a, int b){ 
    if (a == 0) 
        return b; 
    return gcd(b % a, a);
} 

From my understanding of recursion, In recursion, We try to find the answer of a complex problem (general case) using an answer we know (base case)

As the recursion calls stack up we are essentially going to simpler problems until the base case is hit. The base case returns a value, And because of that value being returnes, answers to all the stacked sub problems start bubbling up to the original function call and in the end we arrive to the answer of our problem.

I am not understanding how the value returned by base case is used by the function calls placed above

This is my attempt at dry running the above code (Third one). The function call is

gcd(20,8);

gcd(20,8) -> gcd(8,20) -> gcd(4,8) -> gcd(0,4)

Now we hit the base case with the function call gcd(0,4)

It returned 4

Now how did the previous function call gcd(4,8) use that 4

We are not 'catching' the returned value in any variable, Then what exactly happens to that value and how is the final answer (4 in this case) bubbled up and returned by the original function call?


Solution

  • Consider this example:

    int functionA() {
        return functionB();
    }
    

    This code will call functionB and directly return the result of functionB to the caller of functionA without manipulating it. It is equivalent to writing:

    int functionA() {
        int toReturn = functionB();
        return toReturn;
    }
    

    As you put it the value returned by functionB "is not caught" by an explicitly defined variable in functionA.

    Perhaps the recursion is what confused you but your question is not actually about recursion. It is valid for any function call.