Python 如何求二者的最大幂
我正在尝试创建一个程序,以找到小于或等于给定数字的两个最大幂 下面是我为它编写的代码:Python 如何求二者的最大幂,python,python-3.x,Python,Python 3.x,我正在尝试创建一个程序,以找到小于或等于给定数字的两个最大幂 下面是我为它编写的代码: boundary = int(input("Enter your number: ")) x = boundary ctr = 0 if x % 2 == 0: while x >= 0: x /= 2 ctr += 1 else: ctr = 0 w
boundary = int(input("Enter your number: "))
x = boundary
ctr = 0
if x % 2 == 0:
while x >= 0:
x /= 2
ctr += 1
else:
ctr = 0
while x >= 1:
x /= 2
ctr += 1
ctr -= 1
它似乎只适用于奇数(else语句部分),并且在输入偶数时不输出任何内容。
我想知道我做错了什么。解决这个问题的一种方法是计算两的每一次幂,并检查它是否小于或等于给定的边界
def highest_power2_loe(boundary):
"""Return the highest power of two less than or equal to `boundary`.
"""
power = 0
while 2**power <= boundary:
power += 1
return power - 1
highest_power2_low(10) # == 3
def最高功率(边界):
“”“返回小于或等于'boundary'的两个最大幂。”。
"""
功率=0
而2**power为什么要区别对待奇数和偶数?
在我看来,奇数的算法对这两种情况都适用:
boundary = int(input("Enter your number: "))
x = boundary
ctr = 0
while x >= 1:
x /= 2
ctr += 1
ctr -= 1
print(boundary, ctr, 2**ctr)
使用循环是解决此问题的一种非常低效的方法
请注意,所需的指数比二进制的边界长度
小一
因此,找到答案的一个有效方法就是使用
power=boundary.bit_length()-1
x=1从answer=1
开始,只要结果小于您的输入,就将其乘以2:
boundary = int(input("..."))
answer = 1
while True:
tmp = answer * 2
if tmp > boundary:
break
answer = tmp
print("{} is less than or equal to {}".format(answer, boundary)
“小于或等于给定数字”SimonF,编辑,感谢您的更正@Nico,在我看来,代码是非常自解释的,变量的名称很好,并且只使用了非常基本的操作。有什么你不懂的地方吗?@Arrandoff这不是关于Nico理解你的代码。这是关于Python新手的。很明显,人们对此很挣扎,否则他们就不会问这个问题了。您的方法与问题中的代码非常不同。这两个都是很好的解释理由。下一次我将添加一个解释,可能重复Do not use循环以二进制方式执行log2操作,这非常低效
boundary = int(input("..."))
answer = 1
while True:
tmp = answer * 2
if tmp > boundary:
break
answer = tmp
print("{} is less than or equal to {}".format(answer, boundary)