26 lines
934 B
Python
26 lines
934 B
Python
|
# 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="")
|