【发布时间】:2012-04-07 08:11:02
【问题描述】:
我知道使用“for”可能会使代码变得清晰,但我想了解为什么这段代码不起作用。 此外,该代码是对 2008 年 MIT OCW 课程练习的改编,其中允许使用的唯一函数是算术函数,if、elif、else、print 和 while。 需要指出的是,代码应该打印出前 1000 个素数。
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。 第一个 while 测试 primecounter 并且由于 primesupport 小于 1000,它进入循环。 然后,primesupport 值更改为 1,因为 3/2=1 由于primesupport大于0,所以进入第二个while循环。 if 条件为真(3%1=0)所以代码输入 if,将 primesupport 更改为 -1 并将 primesofar 增加 2。(现在 primesupport=-1 和 primesofar=5) 这里有一个问题,因为它没有打印 3 就离开了,但让我们继续。 当它回到第二个 while 时,它会收到一个 False,因为 -1 不大于 0。 这将使代码在第一个 while 中进行测试,并且由于 primecounter 没有更改,它将再次进入循环。 Primesupport 现在将获得 2(因为 5/2=2) 它将进入第二个循环并通过所有循环,直到出现 else 条件。 Primesupport 将减一(primesupport now =1),while 循环将继续进入 elif。 那将打印 5 将 primesofar 增加到 7 减少 primesupport 以离开 while 循环并增加 primecounter,返回第一个循环并重新开始。 我承认,除了没有按预期打印的 3 之外,我看不出我在哪里犯了错误。希望你能指出我。
感谢大家的帮助,特别是 FallenAngel、John Machin、DiamRem 和 Karl Knechtel 指出错误并展示了调试方法。
【问题讨论】:
-
它卡住了,我必须按 ctrl+c 它可能会结束一些无限循环
-
另外,你确定你的缩进是正确的吗?更具体地说,
primesupport=primesofar/2行是否在第一个 while 循环中正确缩进? -
@Sensato sp 你调试了吗?哪个回路受到影响?循环变量的值是多少?
-
或者
primesupport=primesofar/2不是整数? -
@Kshitij:是的,缩进是对的,我只是在这里手动让它出现在代码框中。
标签: python