編寫一個 Python 程序,使用 For 循環、While 循環和函數來查找質數。除 1 以外不能被任何其他數整除的自然數,其本身稱為質數。
質數:2、3、5、7、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67、71、73、79、83、89、97、101、103、107、109 等。2 是唯一的偶數。
使用 For 循環尋找質數的 Python 程序
該程序允許用戶輸入任何整數值。接下來,這個 Python 程序使用 For 循環檢查給定的數字是否是質數。
Number = int(input(" Please Enter any Number: "))
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
print(" %d is a Prime Number" %Number)
else:
print(" %d is not a Prime Number" %Number)
在 for 循環中,有一個 If 語句來檢查被 I 整除的值是否正好等於 0。如果條件為真,則計數值遞增,然後執行中斷語句。接下來,我們使用另一個 If 語句來檢查 Count 是否為零,Num 是否不等於 1。
用戶在上面的 Python 程序中輸入整數來檢查質數示例是 365
第一次迭代:對於 I 在範圍(2,365//2)
意味着,對於 I 在範圍(2,182.5)–條件為真
現在,檢查 if 條件–if(365% 2 = = 0)。如你所知,條件是假的
接下來,我變成 3
對剩餘的和迭代進行同樣的操作
接下來,進入 Python If 語句。如果(計數== 0 & &個數!= 1 ).在上面的所有迭代中,如果條件失敗,那麼計數值沒有從初始化 0 開始增加。我們使用的是 365(不是零)。所以,條件是真,也就是質數。
使用 While 循環尋找質數的 Python 程序
這個 Python 程序和上面的一樣。我們剛剛將上面 python 程序中的 For 循環替換為 While 。
Number = int(input(" Please Enter any Num: "))
count = 0
i = 2
while(i <= Number//2):
if(Number % i == 0):
count = count + 1
break
i = i + 1
if (count == 0 and Number != 1):
print(" %d is a Prime" %Num)
else:
print(" %d is not a Prime" %Num)
Please Enter any Num: 14
14 is not a Prime
>>>
Please Enter any Num: 109
109 is a Prime
用函數求質數的 Python 程序
這個 python 程序與第一個示例相同。然而,我們通過定義新的函數來分離邏輯。
def finding_factors(Number):
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
return count
Num = int(input(" Please Enter any Num: "))
cnt = finding_factors(Num)
if (cnt == 0 and Num != 1):
print(" %d is a Prime" %Num)
else:
print(" %d is not a Prime" %Num)
Please Enter any Num: 44
44 is not a Prime
>>>
Please Enter any Num: 139
139 is a Prime
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/275750.html