【问题标题】:why doesn't my code seemingly work with odd numbers [duplicate]为什么我的代码似乎不适用于奇数[重复]
【发布时间】:2021-11-13 14:23:59
【问题描述】:

我正在尝试编写将数字分解为其素数分解的代码。到目前为止它适用于偶数,但是当我尝试奇数时它会卡住。我不知道为什么会这样。我没有收到错误,它只是停止执行任何操作。

代码:

priemwaarde = 100
priemgetallen = []
nonpriemgetallen = []
for x in range(2,priemwaarde):
    prime = True
    for i in range(2,x):
        if x % i  == 0:
            prime = False
    if prime == False:
        nonpriemgetallen.append(x)
    else:
        priemgetallen.append(x)

def PriemFactoren(getal):
    factoren = []
    a = getal
    while a not in priemgetallen:
        for priem in priemgetallen:
            if a % priem == 0:
                factoren.append(priem)
                a = a / priem
    a = int(a)
    if getal not in priemgetallen:
        factoren.append(a)
    return factoren
print(PriemFactoren(56))
print(PriemFactoren(55))

【问题讨论】:

    标签: python prime-factoring


    【解决方案1】:

    如果您在while 循环中添加打印语句或调试断点,您会发现它被卡住了,因为a 的值最终为1,并且无法在priemgetallen 中找到它。

    打破想到的无限循环的快速解决方法是将其添加到列表中:

    priemgetallen.append(1)
    

    我想另一种选择是显式处理该值,所以这样的事情也应该打破无限循环:

    def PriemFactoren(getal):
        factoren = []
        a = getal
        while a not in priemgetallen:
            #### Added lines
            if a == 1:
                break
            #### End
            for priem in priemgetallen:
                if a % priem == 0:
                    factoren.append(priem)
                    a = a / priem
        a = int(a)
        if getal not in priemgetallen:
            factoren.append(a)
        return factoren
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-03
      • 2010-12-23
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多