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

26 lines
934 B
Python
Raw Permalink Normal View History

# Program: sumPrimes_v2.py (Report comments/bugs to chikh@yuntech.edu.tw)
# Function: 計算[a,b]區間內所有質數的和
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("""
***********************************
* 計算[a,b]區間內所有質數的和程式 *
***********************************\n""")
inputStr = input("輸入[a,b] ==> ")
argList = inputStr.lstrip(" [").rstrip("] ").split(",")
a, b = eval(argList[0]), eval(argList[1])
sumPrimes = 0
for x in range(a,b+1):
if isPrime(x): #檢查x是否為質數若是把x累加到sum之中
print("發現質數",x)
sumPrimes += x
print("[",a,",",b,"]區間內所有質數的和 = ",sumPrimes,sep="")