c++recursion

Recursive function (help me understand it by pen and paper)


First of all I have to say that I can use recursive functions on easy examples like Fibonacci, but I can't understand how to dry run (solve with pen and paper) this recursion :

#include<iostream>
using namespace std;

int max(int a, int b)
{
    if(a>b)return a;
    return b;
}

int f(int a, int b)
{
    if(a==0)return b;
    return max( f(a-1,2*b), f(a-1,2*b+1) );
}

int main()
{ 
    cout<<f(8,0);
}

How do I do this with pen and paper, with say, a = 5 and b = 6?


Solution

    1. We have always a depth of a (8)
    2. Each invocations calls itself 2 times, once 2b and once 2b+1 is passed
    3. The greater result of both calls is returned
    4. As 2b + 1 > 2b only the right site of the max call is meaningful (2b + 1)

    Now lets do the first iterations mathematically:

    2 * b + 1                           = 2^1 * b + 2^0
    2 * (2^1 * b + 2^0) + 1             = 2^2 * b + 2^1 + 2^0
    2 * (2^2 * b + 2^1 + 2^0) + 1       = 2^3 * b + 2^2 + 2^1 + 2^0
    2 * (2^3 * b + 2^2 + 2^1 + 2^0) + 1 = 2^4 * b + 2^3 + 2^2 + 2^1 + 2^0
    

    As you can see there is a system behind it. Because b = 0 for the first iteration, we can ignore the left side. The final value is thus:

    2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6 + 2^7
    =
    1 + 2 + 4 + 8 + 16 + 32 + 64 + 128
    = 
    255
    

    If we run the programm we get the exact same value