#(python code)
def is_power_of_two(n):
import math
if n <= 0:
return False
power = round(math.log(n, 2))
return 2 ** power == n #(python code)
def is_power_of_two(n):
import math
if n <= 0:
return False
power = round(math.log(n, 2))
return 2 ** power == nThat was Java and your example is in Python, there could be some difference. If you try and compare in Python, please tell us the result.
I then modified the test[1] to look for inconsistencies where they were most likely to be found, ie ±1 of 2n. I reached n being 1024 before python complained about a 'Result too large'.
[0] http://paste.pound-python.org/show/10067/
[1] http://paste.pound-python.org/show/10068/
Edit: just reread about the 1 in 2 billion chance, I'll leave the first test running longer to make sure.
I tested all 2^31 non-negative integers, which is 2147483648 values. If I remember correctly, the value that was wrong was large, probably between 2^30 and 2^31. Java is pretty fast and I think this took tens of minutes. Python is about 20 times slower so it may take hours for you.
>>> is_power_of_two(2 ** 31 - 1)
False
>>> is_power_of_two(2 ** 31)
True
>>> is_power_of_two(2 ** 31 + 1)
False
>>> is_power_of_two(2 ** 548 - 1)
False
>>> is_power_of_two(2 ** 548)
True
>>> is_power_of_two(2 ** 548 + 1)
False