python中的丑数

问题描述 投票:-3回答:2

输入一个数字,如果该数字只能被2、4、5及其幂除,则输出True。我是一个初学者,我不知道自己的代码出了什么问题,它产生了错误的结果。

n = int(input("n: "))
def ugly_number(n):
    while n % 2 != 0:
        n = n/2
    while n % 3 != 0:
        n = n/3
    while n % 5 != 0:
        n = n/5
    if n == 1:
        return True
    else: return False
print(ugly_number(n))
python
2个回答
2
投票

您必须执行while n%mod == 0而不是!= 0,因为那样的话,您就是将任何不可分割的数字除以0,而不要触摸任何可分割的数字。


0
投票

您的条件倒退。您需要将数字除以质数235,以获得剩余因子。如果结果因子不是1,则它必须具有其他质数因子。

def ugly_number(n):
    while n % 2 == 0:
        n = n/2
    while n % 3 == 0:
        n = n/3
    while n % 5 == 0:
        n = n/5
    return n == 1

for number in [6, 8, 14]:
    print(number, ugly_number(number))
6 True
8 True
14 False
© www.soinside.com 2019 - 2024. All rights reserved.