How do I find the sum of prime numbers in a given

2019-02-21 04:44发布

问题:

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

回答1:

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

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


回答2:

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:

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


回答3:

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)