如何将所有这些质数相加?

我正在使用python并尝试创建一个函数,该函数将生成从1到1000的所有PRIME数字,然后将所有的质数相加。到目前为止,我已经到达所有素数的打印位置,但是我对如何将它们相加感到困惑。这是我的代码:

lower = 0
upper = 1000

for num in range(lower, upper + 1):
   # all prime numbers are greater than 1
   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num)
评论
  • Dear
    Dear 回复
    lower = 0
    upper = 1000
    The_list = []
    
    for num in range(lower, upper + 1):
       # all prime numbers are greater than 1
       if num > 1:
           for i in range(2, num):
               if (num % i) == 0:
                   break
           else:
               print(num)
               The_list.append(num)
    print(The_list)
    
  • O哦
    O哦 回复

    Just create an empty list before the loop, then when you determine which numbers are prime, append them to the list, and at the end call sum()

    lower = 0
    upper = 1000
    primes=[]
    
    for num in range(lower, upper + 1):
       # all prime numbers are greater than 1
       if num > 1:
           for i in range(2, num):
               if (num % i) == 0:
                   break
           else:
               primes.append(num)
    
    print(sum(primes))
    
  • phic
    phic 回复

    Use a sum variable and add the num into it:

    lower = 0
    upper = 1000
    sum = 0
    for num in range(lower, upper + 1):
       # all prime numbers are greater than 1
       if num > 1:
           for i in range(2, num):
               if (num % i) == 0:
                   break
           else:
               print(num)
               sum += num
    print(sum)
    

    输出:

    2   3   5   7   11   13      。 。 。      971   977   983   991   997   质数和:76127