且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 3.5 中找到给定范围内的素数总和?

更新时间:2022-05-05 05:50:47

在您的情况下,a 是循环中使用的整数变量,不是 可迭代的.

In your case, a is an integer variable being used in your loop, not an iterable.

import numpy as np

num = int(input("Enter a number: "))

primes = []

for a in range(2,num+1):

  maxInt= int(np.sqrt(a)) + 1

  for i in range(2,maxInt):

    if (a%i==0):
      break

  else:
    primes.append(a)

print(sum(primes))

因此,如果我们只是将它们附加到列表中而不是打印它们,当获取列表 primessum 时,我们会得到以下输出.

So if we just append them to a list as we go instead of printing them, we get the following output when taking the sum of the list primes.

Enter a number: 43
281