对于给定x < 10^15
,快速准确地确定最大整数p
,使得2^p <= x
以下是我尝试过的一些事情:
首先,我尝试了这个,但对于大量数字并不准确:
>>> from math import log
>>> x = 2**3
>>> x
8
>>> p = int(log(x, 2))
>>> 2**p == x
True
>>> x = 2**50
>>> p = int(log(x, 2))
>>> 2**p == x #not accurate for large numbers?
False
我可以尝试类似:
p = 1
i = 1
while True:
if i * 2 > n:
break
i *= 2
p += 1
not_p = n - p
如果 p 为 50,则最多需要 50 次操作
我可以预先计算 2 的所有幂,直到 2^50,然后使用二分搜索找到 p。这将需要 log(50) 操作,但看起来有点过分和丑陋?
我为基于 C 的解决方案找到了这个线程:Compute fast log base 2 ceiling
但是它看起来有点难看,我不确定如何将它转换为 python。