开发者

Python loop that shouldn't work but does anyways [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

So I decided to learn python this weekend and I started with my default hello world, the prime solver. This code shouldn't work... But for whatever reason it does (for numbers 5 and higher.)

#!/usr/bin/python
a = 2
while a < 65535:
    c = 0
    a = a + 1
    b = 2
    while b != a:
        if a % b == 0:
            #print a, "is no开发者_开发百科t prime. LCD is ", b
            break
        b = b + 1
     if a - 1 == b: c = 1
 if c == 1: print a, " is prime"

The next to the last conditional should always be false, and yet somehow a -1 == b for all primes 5 and up.

Can someone point out this noob's mistake, because I'm obviously missing something easily described.

Answers further below.


If a is not prime, it has atleast two proper divisors, and of one of them must be smaller than the square root (or both are the square root). If b reaches sqrt(a)+1, then a must be prime. So if b reaches a - 1, you can be pretty sure it's prime. You could also replace it by if a - 3 == b, or a / 2 (but this might not work for the smaller primes).


It seems to work for me; after changing 65535 to 1024 and removing the " is prime" portion (so I can run the results right into factor(1)), the output looks like this:

$ ./prime.py | xargs -n1 factor > /tmp/list ; wc -l list
170 list
$ head list
5: 5
7: 7
11: 11
13: 13
17: 17
19: 19
23: 23
29: 29
31: 31
37: 37

Are you sure you copy-and-pasted it correctly? I find one-space indents miserable reading, and perhaps you mis-copied or mis-formatted?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜