Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand how this function works and how it comes to the result of 60

def A(x, y):
    if x == 0:
        return y + 2
    if y == 0:
        return A(x - 1, 1) + 1
    return A(x - 1, A(x, y - 1)) * 2

print(A(1, 3))

The output is 60. I ran the code but I have no clue how you get to that value. Sorry for the rather dumb question.

like image 819
Slurm Avatar asked Nov 29 '25 20:11

Slurm


1 Answers

A appears to be recursive, so when you call A(1,3), it keeps calling itself.

Let's walk through it:

  • The first time you run it, x != 0, so it doesn't return y+2

  • y != 0, so it doesn't return A(x-1, 1) + 1

  • Instead, it returns A(x-1, A(x, y-1)) * 2

A view of this can be summarised as:

A(1,3):
    return A(x-1, A(x, y-1)) * 2
    return A(0, A(1, 2)) * 2:
        A(1,2):
            return A(x-1, A(x, y-1)) * 2
            return A(0, A(1, 1)) * 2:
                A(1,1):
                    return A(x-1, A(x, y-1)) * 2
                    return A(0, A(1, 0)) * 2:
                        A(1,0):
                            return A(x-1, 1) + 1
                            return A(0, 1) + 1:
                                A(0,1):
                                    return y+2
                                    return 3
                                3 + 1 = 4
                                return 4
                    return A(0,4) * 2:
                        A(0,4):
                            return y+2
                            return 6
                        6*2 = 12
                    return 12
            return A(0, 12) * 2:
                A(0,12):
                    return y+2
                    return 14
                14*2 = 28
            return 28
    return A(0, 28) * 2:
        A(0,28):
            return y+2
            return 30
        30 * 2 = 60
    return 60

Hopefully that 'tree' helps you visualise what is going on.

like image 165
Ed Ward Avatar answered Dec 01 '25 09:12

Ed Ward