簡體   English   中英

無法在python中找到素數代碼中的錯誤

[英]Unable to find the mistake in prime number code in python

n=5;count=2;i=3;j=2;
while (count <= n):
    for j in range (2,i):
            if(i%j == 0):           
                break
    if(j==i):
        print i
        count = count +1
    i = i+1

我試圖找到前n個素數但不知何故這個代碼似乎沒有編譯。 該程序陷入了for循環 我嘗試使用相同的邏輯在C語言中編寫代碼,但效果似乎不錯,但是由於我需要大量支持,因此python似乎是顯而易見的選擇,因此希望在python中運行。 任何幫助都會很棒。

range(a, b)ab-1

n=5;count=2;i=3;j=2;
while (count <= n):
    for j in range (2,i):
        if(i%j == 0):           
            break
    if(j==i-1):
        print i
        count = count +1
    i = i+1

我打賭你有

 int j;
 for(j = 2; j < i; j++) {
 }

因此,在質數循環結束時, j將為i

使用range時,Python不會超出限制。

這對於循環之后的else:關鍵字的其他模糊語法很有用。 正如其他人所評論的那樣,成功完成for循環的測試結果是一個。

相反,嘗試使用else來測試是否成功完成:

for j in range (2,i):
        if(i%j == 0):
            break
else:
    print i
    count = count +1

你的問題在這里:

for j in range (2,i):

這檢查j = 2,3,4 .... i-1。 因此,您的代碼永遠不會運行:

if(j==i):
        print i
        count = count +1

因此計數永遠不會改變。 因此,您將獲得一個無限的while循環。 將支票更改為

if(j==i-1):
        print i
        count = count +1

在Python 3中,它是print() ,而不是print 更改此行時代碼將編譯:

        print(i)

你似乎也有一個無限循環,但我會讓你調試它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM