Re: [問題] 找前 40 個質數出現奇怪的問題
※ 引述《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
推
11/13 14:08, , 1F
11/13 14:08, 1F
→
11/13 15:53, , 2F
11/13 15:53, 2F
→
11/13 15:55, , 3F
11/13 15:55, 3F
嗯,誤題了。就改成:
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)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 6 篇):