24 lines
844 B
Python
24 lines
844 B
Python
# Program: sumPrimes_v1.py (Report comments/bugs to chikh@yuntech.edu.tw)
|
||
# Function: 計算2+3+5+…+N所有質數的和
|
||
|
||
def isPrime(n): #定義函式接受輸入n,檢視n是否為質數並回傳布林值結果(若回傳True,代表n為質數;回傳False,代表n不為質數)
|
||
for i in range(2,n):
|
||
if n%i == 0: #n可被i整除,則n顯然不為質數
|
||
return False #告知n不為質數
|
||
return True #回傳n為質數
|
||
|
||
print("""
|
||
***********************************
|
||
* 計算2+3+5+...+N之所有質數和程式 *
|
||
***********************************\n""")
|
||
N = eval(input("輸入N ==> "))
|
||
sumPrimes = 0
|
||
|
||
for x in range(2,N+1):
|
||
if isPrime(x): #檢查x是否為質數,若是,則把x累加到sum之中
|
||
print("發現質數",x)
|
||
lastPrime = x
|
||
sumPrimes += x
|
||
|
||
print("2+3+5+…+",lastPrime,"所有質數的和 = ",sumPrimes,sep='')
|