Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion function (with bit shift)

def recursion(x):
    if x == 0:
        return 0
    else:
        return x << 1 + recursion(x - 1)

print(recursion(3)) # 393216


print(3 << 1) # 6
print(2 << 1) # 4
print(1 << 1) # 2

In my head the output of the recursion function should be: 12 (6+4+2) Why is this not the case? I must say "393216" is slightly bigger than my expected number "12".

My expectation:

--> return 1<<1==2 for 1
--> return 2<<1==4 for 2
--> return 3<<1==6 for 3
0 --> return 0 for 0 

All together = 12

like image 591
Sebastian Nielsen Avatar asked Jun 03 '17 20:06

Sebastian Nielsen


2 Answers

The reason is due to operator precedence. Bitshift operators have lower precedence than arithmetic.

By default, x << 1 + recursion(x - 1) is assumed to be x << (1 + recursion(x - 1)).

You can fix the issue by overriding the default precedence using parentheses.

def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)

print(recursion(3)) # 12
like image 197
cs95 Avatar answered Oct 06 '22 16:10

cs95


Operator precedence. Bit shifts have lower precedence than addition/subtraction (see in docs). Hence you need

def recursion(x):
    if x == 0:
        return 0
    else:
        return (x << 1) + recursion(x - 1)

as currently your function is being interpreted equivalent to

def recursion(x):
    if x == 0:
        return 0
    else:
        return x << (1 + recursion(x - 1))
like image 44
miradulo Avatar answered Oct 06 '22 15:10

miradulo