递归生成 Python 中的素数 2

Recursions to produce the prime numbers in Python 2

我试图使用递归来生成 python 中的素数(因为我发现迭代方法会花费太多时间,特别是如果说一个人想要找到所有素数大约 100 万左右)。这是我的代码:

def primes(n): #to produce prime numbers less than or equal to n
    if n <= 1:
        return "No primes that satisfy"
    elif n == 2:
        return [2]
    else:
        if all(n%a != 0 for a in primes(n-1)): #A number, n, must not be divisible by any of the prime numbers contained in the list primes(n-1)
          k = primes(n-1).append(n)
          return k
        else:
          S = primes(n-1)
          S = primes(n)
          return S
print primes(5)

我收到以下错误 - 类型错误:'NoneType' 对象不可迭代。我只是 Python 的初学者,我不确定这意味着什么。如果有人能指出为什么会出现此错误以及我可以对程序进行哪些改进以避免此错误,我将不胜感激。 谢谢

考虑这个程序片段:

k = primes(n-1).append(n)
return k

list.append() 的 return 值为 None,因此 k = None,您有效地执行了 return None

试试这个:

k = primes(n-1) + [n]

旁白:OP 至少还有一个错误。他们需要删除行 S = primes(n)