Python/Basic/chick_python_exam/Unit1_basic/program/sumPrimes_v1.py

24 lines
844 B
Python
Raw Permalink Normal View History

# 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='')