本文實(shí)例講述了Python實(shí)現(xiàn)的尋找前5個(gè)默尼森數(shù)算法。分享給大家供大家參考,具體如下:
找前5個(gè)默尼森數(shù)。
若P是素?cái)?shù)且M也是素?cái)?shù),并且滿足等式M=2**P-1,則稱M為默尼森數(shù)。例如,P=5,M=2**P-1=31,5和31都是素?cái)?shù),因此31是默尼森數(shù)。
python2代碼如下:
from math import sqrt def isPrime(n): 'judge whether a positive integer is a prime number!' if n==1: return False k=int(sqrt(n)) for i in range(2,k+1): if n%i==0: return False return Truedef getMonisen(n): count=0 l=[] P=2#最小的素?cái)?shù)是2,因此P初值為2 while True: if isPrime(P): M=2**P-1 if isPrime(M): l.append(M) count+=1 if count==n: break P+=1 return ll=getMonisen(5)print l
運(yùn)行程序,結(jié)果如下:
[3, 7, 31, 127, 8191]
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選