求奇除数

问题描述 投票:0回答:2

有一个函数,它找到第一个奇数除数然后返回“YES”或返回“NO”:

def find_del(a: int) -> str:
"""return 'YES' if number have odd divisor else 'NO'."""
if a % 2 != 0:
    return 'YES'
else:
    x = 'NO'
    for j in range(3, a):
        if (a % j == 0 and j % 2 != 0) or (a / j == 0):
            x = 'YES'
            break
    return x

但是这个功能对于号码 1099511627776 来说运行速度不太快。

如何更改功能使其工作?

python division
2个回答
0
投票

感谢“molbdnilo”的提示,我改变了我的程序:

def find_del(a: int) -> str:
"""return Yes if number have odd divisor else No"""
    while a % 2 == 0:
        a = a // 2
    return 'YES' if a != 1 else 'NO'

现在它甚至适用于像 1099511627776 这样的大数字。


0
投票

您需要使用 & 运算符

def find_del(a: int) -> str:
    return "YES" if (n & (n-1)) == 0 else "NO"
© www.soinside.com 2019 - 2024. All rights reserved.