本文介紹了如何在 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
推薦答案
在您的情況下,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))
因此,如果我們只是將它們附加到列表中而不是打印它們,當獲取列表 primes
的 sum
時,我們會得到以下輸出.
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
這篇關于如何在 Python 3.5 中找到給定范圍內的素數總和?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!