《用python玩轉數據》week1編程作業:循環編程題

  • 2020 年 2 月 10 日
  • 筆記

#################

尋找第6個默尼森數

經典程式設計問題:找第n個默尼森數。P是素數且M也是素數,並且滿足等式M=2**P-1,則稱M為默尼森數。

例如,P=5,M=2**P-1=31,5和31都是素數,因此31是默尼森數。

提交方式直接將答案(M的值)寫在txt文件中通過網路提交。

其實這個問題真的很簡單,當你知道如果去判斷一個數是否是素數(一個大於1的自然數,除了1和它本身外,不能被其他自然數(質數)整除)

最後答案為 131071

###################

#code as below  

#define function isprime to check whether number P is prime or not

#loop to generate the final result

# parameter 's' stand for the index of moni prime number

# parameter 'm' means the moni prime

# when s=6 , the m=131071

import  math    def isprime(p):   if p<=1:       return False   for i in range(2,int(math.sqrt(p))+1):       if p%i==0:           return  False   return True    s=0  while s<=6 :   for i in range (1,100):   m=2**i-1       if isprime(i) and isprime(m):           s=s+1           print(i)           print("%0.f is the %0.f moni prime"%(m,s))