作者mathfeel (mathfeel)
看板Python
标题Re: [问题] 找前 40 个质数出现奇怪的问题
时间Sun Nov 13 11:32:33 2011
※ 引述《Equalmusic (Cosmajoonitist)》之铭言:
: i = 0 #dummy index
: x = 3 #prime candidates
: p = 2 #dividers
: print 2 #start from 2
: while (i < 40):
: while (x > p): #get out of the loop only when p >=x
: if x%p != 0:
: p = p + 1
: else: x = x + 1
: print x
: i = i + 1
: x = x + 2
: p = 2
: print 'Done!'
: 我是写程式新手最近刚开始学 Python
: 我想计算前面 40 个质数
: 跑出来多半正确, 质数都没有漏掉, 但却多出来一些不是质数的比如 27 跟 35
: 但我把 27 丢回去怎麽看也不觉得会跑出 loop 之外
: 想请板上先进帮我看一下是怎麽回事...感激不尽 Orz....
这种情况适用Generator:
import math
def isprime(a):
""" assume a is integer > 2 """
for x in range(2, int(math.sqrt(a)) + 1):
if a % x == 0:
return False
return True
def primes_upto(x):
a = 2
while a <= x:
if isprime(a):
yield a
a += 1
if __name__ == '__main__':
p = [ x for x in primes_upto(40) ]
print p
--
In heaven, all the interesting people are missing.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 108.66.116.155
1F:推 kusoayan:cool 11/13 14:08
2F:→ sbrhsieh:写 p = list(primes_upto(40)) 会稍好一点 11/13 15:53
3F:→ sbrhsieh:另,找前 40 个质数和 40 以下的质数是不一样的 11/13 15:55
嗯,误题了。就改成:
def primes_upto(n, a=2):
""" Generates the first n primes >= a """
while n > 0:
if isprime(a):
yield a
n -= 1
a += 1
※ 编辑: mathfeel 来自: 108.66.116.155 (11/14 19:44)