我编写的python3主因子函数无法按预期工作

时间:2019-11-25 00:43:57

标签: python arrays python-3.x function

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。

1 个答案:

答案 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]

一些进一步改进程序的想法:

  • 在if-test中,括号并非总是必需的;习惯上将它们排除在外,以使内容更具可读性。
  • 在大多数编程语言中,标志称为布尔值,其值为True和False。另外,给他们起有意义的名字也有助于理解程序。
  • 现在,您要测试每个小于x的{​​{1}}是否为质数,然后再测试其是否为除数。如果您首先测试除数,那么您不需要检查素数就可以赢得一些时间。另外,一旦发现n不是素数,就可以跳出循环。

以下是建议更改的代码:

x