def primeF (n):
x = 2
factors: List[int] = []
while (x < n):
y = 2
flag = 0
while (y < x):
if (x % y == 0):
flag = 1
y = y + 1
if (n % x == 0 and flag == 0):
factors.append(x)
x = x + 1
return factors
primeF(6)
运行此代码时始终会出现错误,但我不确定为什么。错误消息是:
回溯(最近通话最近):
文件“ C:/Users/User/untitled/EulerQs.py”,第41行,在 print(primeF(6))文件“ C:/Users/User/untitled/EulerQs.py”,第38行,位于primeF中 factor.append(x)MemoryError
我不知道这意味着什么。如果有任何区别,我正在使用PyCharm。
答案 0 :(得分:0)
如评论中所述,崩溃的原因是外部while循环永远不会结束,因为x
的增量在该循环之外。只需更改缩进量即可将x = x + 1
放入循环内。
另一有用的事情是自动写出一系列数字的结果。然后,每次n
本身为质数时,该函数都会给出一个空列表。因此,在外部while循环的停止条件下,还应该允许x == n
。
更改此代码,代码如下:
def primeF (n):
x = 2
factors = []
while (x <= n):
y = 2
flag = 0
while (y < x):
if (x % y == 0):
flag = 1
y = y + 1
if (n % x == 0 and flag == 0):
factors.append(x)
x = x + 1
return factors
for i in range(11):
print(i, "has as prime factors:", primeF(i))
输出:
0 has as prime factors: []
1 has as prime factors: []
2 has as prime factors: [2]
3 has as prime factors: [3]
4 has as prime factors: [2]
5 has as prime factors: [5]
6 has as prime factors: [2, 3]
7 has as prime factors: [7]
8 has as prime factors: [2]
9 has as prime factors: [3]
10 has as prime factors: [2, 5]
一些进一步改进程序的想法:
x
的{{1}}是否为质数,然后再测试其是否为除数。如果您首先测试除数,那么您不需要检查素数就可以赢得一些时间。另外,一旦发现n
不是素数,就可以跳出循环。以下是建议更改的代码:
x