I am using binary search to check if a number is a power of 2. I wrote the code below but for n = 2048 I get "OverflowError: (34, 'Result too large')".
def isPowerOfTwo(n):
if n <= 0:
return False
high = n
low = 0
mid = n/2
print(high, low, mid)
while True:
if mid.is_integer() and 2**mid == n:
print(high, low, mid)
return True
elif mid.is_integer() and 2**mid > n:
print(high, low, mid)
high = mid
mid = (high + low) / 2
elif mid.is_integer() and 2**mid < n:
print(high, low, mid)
low = mid
mid = (high + low) / 2
else:
print(high, low, mid)
return False