"While" 在查找数字的质因数时循环导致错误。并且不能将此程序与高数字一起使用

"While" loop causing error while finding prime factors of a number. And can't use this program with high numbers

创建了一个程序来查找自然数的质因数,但出现错误:

multipliers = []
a = 2
value = input("Put a natural number here: ")
value = int(value)

for i in range(1, value):
    if value % i == 0:
        multipliers.append(i)

for x in multipliers:
    while a < x:
        if x % a == 0:
            multipliers.remove(x)
        else:
            a += 1

print(multipliers)

我想在这里做的是:获取一个输入值,找到一个值的乘数并从中生成一个列表,将这些乘数 1 乘以 1 并尝试除以 [2, 3, 4, 5 ...],如果 a 是 x 的乘数,将其从列表中删除并从列表中获取另一个值作为 x,然后执行相同操作。

但是当我尝试 运行 时,我收到一条错误消息

ValueError: list.remove(x): x not in list

我不知道我哪里做错了。你能帮帮我吗?

因为 x 已从列表中删除 - 然后 while 循环再次循环并尝试再次从列表中删除 x

要解决此问题,请在您的 while 循环中添加一个 break,如下所示:

for x in multipliers:
    while a < x:
        if x % a == 0:
            multipliers.remove(x)
            break
        else:
            a += 1

您还可以用列表理解替换第二个 for 循环:

factors = [x for x in multipliers if all(x % a != 0 for a in range(2, x))]