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"
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
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:
This is perhaps a more idiomatic solution (using a
forloop instead of awhileloop), and works perfectly.The outer
forloop iterates through all the numbers from 2 ton.The inner one iterates to all numbers from 2 to
p. If it reaches a number that divides evenly intop, then it breaks out of the inner loop.The
elseblock executes every time the for loop isn’t broken out of (printing the prime numbers).Then the program prints
'Done'after it finishes.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.