二进制搜索以查看数字是否为2的幂

时间:2019-03-27 18:20:08

标签: python

我正在使用二进制搜索来检查数字是否为2的幂。我编写了以下代码,但对于n = 2048,我得到了“ 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

2 个答案:

答案 0 :(得分:2)

您还可以使用二进制运算(而不是二进制搜索),二进制的to的幂是1,后跟0。这是一种测试方法:

def isPowerOfTwo(n):

    if n <= 0:
        return False

    # get rid of all the trailing zeros
    while not n & 1:
        n >>= 1

    if n != 1:
        return False
    else:
        return True

或者只是(可能更快)

def isPowerOfTwo(n):

    if n <= 0:
        return False
    return bin(n).count("1") == 1

答案 1 :(得分:0)

您可以修改SODIUM_EXPORT int crypto_kx_client_session_keys(unsigned char rx[crypto_kx_SESSIONKEYBYTES], unsigned char tx[crypto_kx_SESSIONKEYBYTES], const unsigned char client_pk[crypto_kx_PUBLICKEYBYTES], const unsigned char client_sk[crypto_kx_SECRETKEYBYTES], const unsigned char server_pk[crypto_kx_PUBLICKEYBYTES]) __attribute__ ((warn_unused_result)); 以涵盖以下三种情况之一:

  1. n,在这种情况下为n = 2
  2. return True非零,所以它不是2的倍数,n % 2
  3. 都不使用return False(整数除法)更新
n //= 2