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?
The results are different because the equivalent of 2 ** n
is 1 << n
, not 2 << n
.
**
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With