javascriptrecursionmutual-recursion

How does this mutual recursion logic work?


The below code returns 39, and I can't understand how the logic works to where it arrives at 39. I keep getting 36 or 43. Can anyone list step by step how this program runs?

a(1);

function a(foo) {
    if(foo> 20) return foo;
    return b(foo+2);    
}

function b(foo) {
    return c(foo) + 1;
}

function c(foo) {
    return a(foo*2);
}

Solution

  • You mentioned that when you tried, you got 36, so I'm guessing that you just forgot that you have to walk back up the call stack and apply the + 1 from the c function. Since this recursion chain ends up invoking c three times, your result is 36 + 3 = 39.

    But, we can go through step by step. All I've done here is listed out each call. We continue down the chain until one of the functions gives us an actual number, then we walk back up and replace each call with the number it returned:

    First call:
    a(1)  -> 1 < 20 so return b(3)     ^ return 39 --> final result: 39
    b(3)  -> return c(3) + 1           │ return 38 + 1 = 39
    c(3)  -> return a(6)               │ return 38
    a(6)  -> 6 < 20 so return b(8)     │ return 38
    b(8)  -> return c(8) + 1           │ return 37 + 1 = 38
    c(8)  -> return a(16)              │ return 37
    a(16) -> 16 < 20 so return b(18)   │ return 37
    b(18) -> return c(18) + 1          │ return 36 + 1 = 37
    c(18) -> return a(36)              │ return 36
    a(36) -> 36 > 20 so return 36 ─────┘