我明白,也许使用“for”的代码可以清楚,但我想了解为什么这段代码不工作。 此外,该代码是2008年MIT OCW课堂练习的改编版本,其中允许使用的唯一函数是算术函数,如果,elif,else,print和while。 只是要指出,代码应该打印出前1000个素数。Python双while循环不工作,不能为什么
print '2, ' #Print the prime 2 to set only odd primes.
primesofar=3 #Set 3 as the first prime
primecounter=1 #Mark 3 as the first prime to test until 1000, otherwise the while below should test to 1001
primesupport=1 #Create primesupport with a integer value
while primecounter<1000:
primesupport=primesofar/2 #Create a support counter for test the prime. This counter only had to have the half value of the supposed prime, because we only need to try to divide by the primes that are lower than the half of the suppposed prime. In fact it would be better to test for values that are lower than the square root of the supposed prime, but we can't use square root operation yet.
while primesupport>0:
if primesofar%primesupport == 0:
primesupport=-1 #If the remainer of the division is 0, the number isn't prime because it will have more than two divisors so we set primesupport as -1 to exit the while and increase the current primesofar to the next odd number.
primesofar=primesofar+2
elif primesupport==1: #If primesupport is 1, we tested all the numbers below the half of the supposed prime which means the number is prime. So we print it, set the while exit and increase the number of primes counted and go to the next odd number.
print primesofar+', '
primesofar=primesofar+2
primesupport=-1
primecounter=primecounter+1
else:
primesupport=primesupport-1
我很高兴得到快速回复,现在我认为可能在代码中有一段时间我看不到。因此,我会尽力写下我认为代码应该做的事情,以便更容易地指出我犯的错误。 开始吧: primesofar收到3; primecounter收到1并且primesupport收到1. 第一次测试primecounter和primesupport之后小于1000,它进入循环。 然后,辅助支持值更改为1,因为3/2 = 1 由于primesupport大于0,它会进入第二个while循环。 如果条件为真(3%1 = 0),所以代码输入if,将primesupport更改为-1并将primesofar增加2(现在primesupport = -1,primesofar = 5) 这里有个问题,因为它不留印3,但让我们继续。 当它回到第二个时,它将收到一个False,因为-1不会大于0. 这将使代码测试第一次,并且由于primecounter没有更改,它将再次进入循环。 Primesupport现在将收到2(因为5/2 = 2) 它将进入第二个循环并遍历所有它直到else条件。 Primesupport将减1(primesupport now = 1),while循环将继续进入elif现在。 这将打印5 将primesofar增加到7 减少primesupport离开while循环并增加primecounter,返回到第一个循环并重新开始。 我承认,除了没有按预期打印的3之外,我无法看到我在这里犯了什么错误。希望你能指出我。
非常感谢大家的帮助,尤其是FallenAngel,John Machin,DiamRem和Karl Knechtel,他们指出了错误并展示了调试方法。
定义“不工作” – 2012-04-07 08:14:19
它卡住了,我必须ctrl + c它可能会结束一些无限循环 – 2012-04-07 08:17:25
也,你确定你的缩进是正确的吗?更具体地说,是在第一个while循环内正确缩进的'primesupport = primesofar/2'行吗? – 2012-04-07 08:18:35