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

前端 未结 3 1761
醉梦人生
醉梦人生 2021-01-16 18:29

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         


        
3条回答
  •  萌比男神i
    2021-01-16 18:44

    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
    

提交回复
热议问题