新聞中心
創(chuàng)新互聯(lián)Python教程:

目前創(chuàng)新互聯(lián)已為成百上千的企業(yè)提供了網(wǎng)站建設、域名、虛擬空間、網(wǎng)站托管運營、企業(yè)網(wǎng)站設計、噶爾網(wǎng)站維護等服務,公司將堅持客戶導向、應用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
編寫一個 Python 程序,使用 For 循環(huán)、While 循環(huán)和函數(shù)來查找質(zhì)數(shù)。除 1 以外不能被任何其他數(shù)整除的自然數(shù),其本身稱為質(zhì)數(shù)。
質(zhì)數(shù):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 是唯一的偶數(shù)。
使用 For 循環(huán)尋找質(zhì)數(shù)的 Python 程序
該程序允許用戶輸入任何整數(shù)值。接下來,這個 Python 程序使用 For 循環(huán)檢查給定的數(shù)字是否是質(zhì)數(shù)。
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 循環(huán)中,有一個 If 語句來檢查被 I 整除的值是否正好等于 0。如果條件為真,則計數(shù)值遞增,然后執(zhí)行中斷語句。接下來,我們使用另一個 If 語句來檢查 Count 是否為零,Num 是否不等于 1。
用戶在上面的 Python 程序中輸入整數(shù)來檢查質(zhì)數(shù)示例是 365
第一次迭代:對于 I 在范圍(2,365//2) 意味著,對于 I 在范圍(2,182.5)–條件為真 現(xiàn)在,檢查 if 條件–if(365% 2 = = 0)。如你所知,條件是假的 接下來,我變成 3
對剩余的和迭代進行同樣的操作
接下來,進入 Python If 語句。如果(計數(shù)== 0 & &個數(shù)!= 1 ).在上面的所有迭代中,如果條件失敗,那么計數(shù)值沒有從初始化 0 開始增加。我們使用的是 365(不是零)。所以,條件是真,也就是質(zhì)數(shù)。
使用 While 循環(huán)尋找質(zhì)數(shù)的 Python 程序
這個 Python 程序和上面的一樣。我們剛剛將上面 python 程序中的 For 循環(huán)替換為 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
用函數(shù)求質(zhì)數(shù)的 Python 程序
這個 python 程序與第一個示例相同。然而,我們通過定義新的函數(shù)來分離邏輯。
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 分享標題:Python程序:尋找質(zhì)數(shù)
當前URL:http://fisionsoft.com.cn/article/dpocsih.html


咨詢
建站咨詢
