您好,登錄后才能下訂單哦!
問題描述:
類似7、37、67、97、107、137、167、197,這樣由素數組成的數列叫做等差素數數列。素數數列具有項數的限制,一般指素數數列的項數有多少個連續項,最多可以存在多少個連續項。
編程找出100以內的等差素數數列。
示例代碼:
解題步驟: #1. 篩法找到100所有素數 #2. 對于素數list內素有倆兩組合,構造等差數列a0, a1項 #3. 計算出a2, 查表判斷a2是否是素數,是素數則能構成素數等差序列, 計算a3... def findAllPrime(n): pt = [True] * n prime = [] for p in range(2, n): if not pt[p]: continue prime.append(p) for i in range(p * p, n, p): pt[i] = False return prime, pt prime, pt = findAllPrime(100) print prime for i in range(len(prime)): for j in range(i + 1, len(prime)): a0, a1 = prime[i], prime[j] an = a1 + a1 - a0 s = [] while an < 100 and pt[an]: s.append(an) an += a1 - a0 if s: print [a0, a1] + s
結果:
[3, 5, 7] [3, 7, 11] [3, 11, 19] [3, 13, 23] [3, 17, 31] [3, 23, 43] [3, 31, 59] [3, 37, 71] [3, 41, 79] [3, 43, 83] [5, 11, 17, 23, 29] [5, 17, 29, 41, 53] [5, 23, 41, 59] [5, 29, 53] [5, 47, 89] [7, 13, 19] [7, 19, 31, 43] [7, 37, 67, 97] [7, 43, 79] [11, 17, 23, 29] [11, 29, 47] [11, 41, 71] [11, 47, 83] [13, 37, 61] [13, 43, 73] [17, 23, 29] [17, 29, 41, 53] [17, 53, 89] [19, 31, 43] [19, 43, 67] [23, 41, 59] [23, 47, 71] [23, 53, 83] [29, 41, 53] [29, 59, 89] [31, 37, 43] [37, 67, 97] [41, 47, 53, 59] [43, 61, 79, 97] [47, 53, 59] [47, 59, 71, 83] [53, 71, 89] [59, 71, 83] [61, 67, 73, 79] [61, 79, 97] [67, 73, 79]
代碼分析:
根據它的解題步驟來說,先是求出100以內的所有素數放到列表prime中,然后對列表中素數兩兩組合構造成等差數列的a0和a1項(實現方法就是用兩個for循環,第一個循環從列表開始到結束,第二個循環從第一個開始位置加一道結束),現在已經知道了等差數列的兩項,那么公差就是二者之差,第三項就是第二項加公差,然后判斷第三項是否小于100且為素數,是的話就是等差素數,并且在根據該值加公差得到下一個數,依次判斷即可
詳細流程:
官方提供了該題的解題視頻:http://www.iqiyi.com/w_19rt5h4qx5.html#vfrm=8-8-0-1
我的代碼:
之前打算用an=a1+(n-1)*d的方式來做的,但是發現有問題,后來借鑒了示例代碼的解題思路,寫出來了,但是發現和示例代碼沒什么兩樣,也貼出來吧。
import math def prime(m): count=0 for i in range(2,int(math.sqrt(m))+1): if m%i==0: count=1 if count==1: return False else: return True x=[] for j in range(2,100): if prime(j): x.append(j) for k in range(len(x)): for l in range(k+1,len(x)): d=x[l]-x[k] res=[] an=x[l]+d while an<100 and an in x: res.append(an) an=an+d if res: print [x[k],x[l]]+res,
結果:
[3, 5, 7] [3, 7, 11] [3, 11, 19] [3, 13, 23] [3, 17, 31] [3, 23, 43] [3, 31, 59] [3, 37, 71] [3, 41, 79] [3, 43, 83] [5, 11, 17, 23, 29] [5, 17, 29, 41, 53] [5, 23, 41, 59] [5, 29, 53] [5, 47, 89] [7, 13, 19] [7, 19, 31, 43] [7, 37, 67, 97] [7, 43, 79] [11, 17, 23, 29] [11, 29, 47] [11, 41, 71] [11, 47, 83] [13, 37, 61] [13, 43, 73] [17, 23, 29] [17, 29, 41, 53] [17, 53, 89] [19, 31, 43] [19, 43, 67] [23, 41, 59] [23, 47, 71] [23, 53, 83] [29, 41, 53] [29, 59, 89] [31, 37, 43] [37, 67, 97] [41, 47, 53, 59] [43, 61, 79, 97] [47, 53, 59] [47, 59, 71, 83] [53, 71, 89] [59, 71, 83] [61, 67, 73, 79] [61, 79, 97] [67, 73, 79]
題目出處:http://www.cheemoedu.com/exercise/27
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。