Re: [問題] 找前 40 個質數出現奇怪的問題

看板Python作者 (mathfeel)時間13年前 (2011/11/13 03:32), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串4/6 (看更多)
※ 引述《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
cool
11/13 14:08, 1F

11/13 15:53, , 2F
寫 p = list(primes_upto(40)) 會稍好一點
11/13 15:53, 2F

11/13 15:55, , 3F
另,找前 40 個質數和 40 以下的質數是不一樣的
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)
文章代碼(AID): #1ElpfLbP (Python)
討論串 (同標題文章)
文章代碼(AID): #1ElpfLbP (Python)