Python 初学者循环(寻找素数) [英] Python Beginner's Loop (Finding Primes)
问题描述
我确实是 Python 的初学者,所以我为缺乏知识表示歉意,但我问的原因是阅读 Python 手册和教程(http://docs.python.org/2.7/tutorial) 我不是无法完全掌握循环的工作原理.我写了一些简单的程序,所以我想我已经掌握了基础知识,但是无论出于何种原因,这个旨在列出所有小于或等于 n 的素数的程序都不起作用:
I'm truly a beginner at python so I apologise for the lack of knowledge, but the reason I'm asking is that reading the Python manual and tutorial (http://docs.python.org/2.7/tutorial) I'm not unable to totally grasp how loops work. I've written some simple programs so I think I get the basics but for whatever reason this program that is meant to list all primes less than or equal to n is not working:
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
print "Done"
例如我输入 100 时的输出是:
The output when I enter 100 for example is:
2 3 5 7 11 13 17 19 23 27 29 31 35 37 41 43 47 53 59 61 67 71 73 79 83 87 89 95 97 101 Done
这看起来几乎是正确的,但由于某种原因包含 27、35、95,当然它们是复合的.我一直在尝试区分我的循环的工作方式,但我只是没有看到它突然跳过检查可分性的地方.我想,如果有人看一眼,他们可以向我解释导致这种情况的语法是什么.非常感谢!
Which looks almost right but for some reason contains 27, 35, 95, which are composite of course. I've been trying to pick apart the way my loop works but I just don't see where it skips checking for divisibility suddenly. I figured that if someone had a look they could explain to me what about the syntax is causing this. Thanks a bunch!
推荐答案
我实际上会将程序重构为如下所示:
I would actually restructure the program to look like this:
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p,
print 'Done'
这可能是一个更惯用的解决方案(使用 for
循环而不是 while
循环),并且效果很好.
This is perhaps a more idiomatic solution (using a for
loop instead of a while
loop), and works perfectly.
外部 for
循环遍历从 2 到 n
的所有数字.
The outer for
loop iterates through all the numbers from 2 to n
.
内部一个迭代从 2 到 p
的所有数字.如果它达到一个可以整除 p
的数字,则它会跳出内部循环.
The inner one iterates to all numbers from 2 to p
. If it reaches a number that divides evenly into p
, then it breaks out of the inner loop.
else
块在每次 for 循环没有中断时执行(打印质数).
The else
block executes every time the for loop isn't broken out of (printing the prime numbers).
然后程序在完成后打印'Done'
.
Then the program prints 'Done'
after it finishes.
作为旁注,您只需要遍历 2 到 p
的平方根,因为每个因子都有一对.如果你没有得到匹配,那么平方根之后就不会有任何其他因素,这个数字就是质数.
As a side note, you only need to iterate through 2 to the square root of p
, since each factor has a pair. If you don't get a match there won't be any other factors after the square root, and the number will be prime.
这篇关于Python 初学者循环(寻找素数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!