Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between (**) and (<<) in python?

a = 100000000
c = (2**(a-1))-1
b = (2<<(a-1))-1
m = 1000000007
print b%m
print c%m

Output :

494499947
247249973

I am using ** and << operator in python to find powers of 2 raised to a very large number . However similar operations give different result. Just curious why?

like image 575
Harshit Avatar asked Nov 09 '13 20:11

Harshit


2 Answers

The results are different because the equivalent of 2 ** n is 1 << n, not 2 << n.

like image 97
NPE Avatar answered Sep 29 '22 10:09

NPE


** is the exponent operator. << shifts bits to the left.

Because of the nature of binary numbers, for ever step shifting bits to the left doubles the number. As such you can express the same operation as 2 to the power number-of-shifts minus one:

>>> 1 << 1  # 00000001 becomes 0000010
2
>>> 1 << 2  # 00000001 becomes 0000100
4
>>> 1 << 15 # 000000000000001 becomes 1000000000000000
32768

The exponent operator serves to produce exponents of more than just the number 2, however:

>>> 3 ** 3
27

Note however that 2 ** 1 is still two, but shifting to once to the left (2 << 1) is equivalent to 2 ** 2:

>>> 2 ** 1
2
>>> 2 << 1
4
like image 28
Martijn Pieters Avatar answered Sep 29 '22 08:09

Martijn Pieters