简体   繁体   English

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

[英]How do I find the sum of prime numbers in a given range in Python 3.5?

I managed to create a list of prime numbers in a given range using this: 我设法使用以下方法在给定范围内创建素数列表:

import numpy as np  

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

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: 
    print (a)

I want to now find the sum of all of the prime numbers in the range so I just put down 我现在想找到范围内所有质数的总和,所以我放下

print (sum(a))

But when trying to do that, I get the following traceback: 但是,当尝试这样做时,我得到以下回溯:

Traceback (most recent call last):
  File "C:/Users/Jason/PycharmProjects/stackidiots/scipuy.py", line 11, in <module>
    print(sum(a))
TypeError: 'int' object is not iterable

In your case, a is an integer variable being used in your loop, not an iterable. 在您的情况下, a是循环中使用的整数变量, 而不是迭代变量。

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))

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 . 因此,如果我们将它们随即添加到列表中而不是打印它们,则在获取列表primes sum时会得到以下输出。

Enter a number: 43
281

If you want to use sum , you could make a generator function, yielding each a in the loop so you have an iterable to call sum on: 如果要使用sum ,则可以创建一个生成器函数,在循环中产生每个a ,以便您可以迭代调用sum:

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

def sum_range(num):
    for a in range(2, num + 1):
        maxInt = int(a **.5) + 1 
        for i in range(2, maxInt):
            if a % i == 0:
                break
        else:
            yield a

print(sum(sum_range(num)))

Sum them inside the loop 在循环内求和

import numpy as np  

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

result=0
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: 
      print (a)
      result+=a

print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM