我試圖在3之後生成第一個「n」素數。問題是我不明白我的代碼出錯了,並希望有人能夠幫助我處理邏輯。Python素數編碼
a = 3
b = 2
# n = number of prime numbers to be printed.
n = 1000
for a in range(a, n): #This i the range of all numbers to be tested
if a % 2 == 0: #Only odd numbers are prime(except 2) so eliminate the evens
print "."
else:
for b in range(b, a): #This is to test the odd numbers
if (a % b == 0): #I am dividing a by all numbers smaller than it to test
print a, "is not prime"
break
任何指導幫助我解決這個問題將不勝感激。我閱讀了關於這個問題的舊帖子,但想知道我自己的邏輯在哪裏有缺陷。
謝謝。
如果這真的是你的代碼看起來的樣子,那麼'else'就會有錯誤的縮進。 – 2014-09-25 20:00:03
你有壞的縮進!'else'必須低於'if' – Kasramvd 2014-09-25 20:02:16
我會說不要在範圍內(a,n):',對下界和索引器使用相同的變量,儘管它確實做它應該做的事情。此外,你沒有找到第一個'n'的素數,而是找到'n'的素數。 – mixedmath 2014-09-25 20:03:08