Question

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?

Was it helpful?

Solution 3

2**4 = 2^4 = 2*2*2*2

>>> 2**4 
16

2<<4 = Shift left 4 bits: Before shift, 2 is 10 in binary; After shift, 2 is 100000 in binary

>>> 2<<4 
32

OTHER TIPS

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

The << operator means left shift. It is not the same as power of two, although it can be used to compute it.

As an example:

0b10101 << 1 ==> 0b101010
0b1000  >> 1 ==> 0b100
0b10    << 2 ==> 0b1000

To use left shift-operation to compute the power of two you can define a function like this:

def poweroftwo(x):
    return 1 << x
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top