2012-01-03 148 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 

问题,如果没有候选人%计,你得到无限循环。