如何找到两个最大的幂

时间:2019-02-03 19:17:23

标签: python python-3.x

我正在尝试创建一个程序,以查找小于或等于给定数字的2的最大幂。

以下是我为此编写的代码:

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语句部分),并且在输入偶数时不输出任何内容。 我想知道我在这里做错了。

4 个答案:

答案 0 :(得分:0)

为什么您应该区别对待奇数和偶数? 在我看来,奇数算法对两种方法都适用:

boundary = int(input("Enter your number: "))
x = boundary
ctr = 0
while x >= 1:
    x /= 2
    ctr += 1
ctr -= 1

print(boundary, ctr, 2**ctr)

答案 1 :(得分:0)

使用循环是解决此问题的非常无效的方法。

请注意,所需指数比二进制文件boundary的长度小一。

找到答案的有效方法是使用int.bit_length()

power = boundary.bit_length() - 1
x = 1 << power

答案 2 :(得分:0)

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)

答案 3 :(得分:-1)

解决这个问题的一种方法是评估每个2的幂并检查它是否小于或等于给定的边界。

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

请注意,您必须返回power - 1,因为仅当(2**power <= boundary) == False时循环才停止,只有2**power实际上大于boundary时,循环才停止。