2012-01-03 161 views
1

在Python中使用程序打印出前1000個素數(2除外)。所有我能得到的輸出是數字3.不明白我的循環結束的地點或時間。在編程方面非常新穎。任何人都可以幫忙嗎?爲什麼我的嵌套while循環無法正常工作

primeCounter = 1 
candidate = 3 

while primeCounter < 1000: 
    isPrime = True 
    counter = 2 
    while counter < candidate: 
     if candidate%counter == 0: 
      isPrime = False 
     else: 
      counter = counter + 1 

    if isPrime == True: 
     print candidate 
     primeCounter = primeCounter + 1 

    candidate = candidate + 1 
+0

您是否嘗試過調試它?也許通過讓它輸出測試條件等變量的值? – 2012-01-03 03:57:27

回答

3
primeCounter = 1 
candidate = 3 

while primeCounter < 1000: 
    isPrime = True 
    counter = 2 
    while counter < candidate: 
     if candidate%counter == 0: 
      isPrime = False 
      break # <<<<<<<<<<<<<<<<< break here, or the loop will go infinite 
     else: 
      counter = counter + 1 

    if isPrime == True: 
     print candidate 
     primeCounter = primeCounter + 1 

    candidate = candidate + 1 
+0

現在完美。謝謝 – patch321 2012-01-03 03:54:05

2

一旦您設置isPrimeFalse,你不會再增加counter,這樣你就永遠走不出內while循環。

+0

這也工作。謝謝 – patch321 2012-01-03 03:55:44

0

你在塊

while counter < candidate: 
    if candidate%counter == 0: 
     isPrime = False 

問題,如果沒有候選人%計,你得到無限循環。

相關問題