PTA 7-4 素數等差數列 (20 分)

題目

2004 年,陶哲軒(Terence Tao)和本·格林(Ben Green)證明了:對於任意大的 n,均存在 n 項全由素數組成的等差數列。例如 { 7,37,67,97,127,157 } 是 n=6 的解。本題就請你對給定的 n 在指定範圍內找出一組最大的解。

輸入格式:
輸入在一行中給出兩個正整數:n(≤10)爲等差素數數列的項數; MAXP (2≤MAXP<10
5
)爲數列中最大素數的上界。

輸出格式:
如果解存在,則在一行中按遞增序輸出等差最大的一組解;若解不唯一,則輸出首數最大的一組解。若解不存在,則輸出不超過 MAXP 的最大素數。同行數字間以一個空格分隔,行首尾不得有多餘空格。

輸入樣例 1:
5 1000
結尾無空行
輸出樣例 1:
23 263 503 743 983
結尾無空行
輸入樣例 2:
10 200
結尾無空行
輸出樣例 2:
199
結尾無空行

解題思路

n, MAXP = map(int,input().split())
# n, MAXP = map(int,"5 1000".split())
# n, MAXP = map(int,"10 2".split())


import math
def isSushu(input:int)->bool:
    if input == 2 or input == 3 or input == 1:
        return True
    sqrtInt = int(math.sqrt(input))
    for i in range(2,sqrtInt+1):
        if input%i == 0:
            return False
    return True
sushuList = []
for i in range(2,MAXP+1):
    if isSushu(i) == True:
        sushuList.append(i)
# print(sushuList)
if len(sushuList) == 0:
    print("")
resList = []
for index,val in enumerate(sushuList):
    for i in sushuList[index+1:]:
        dengcha = i - val
        shifoucunzai = True##是否存在等差數列
        for chengshu in range(1,n):
            dengchashu = val + dengcha*(chengshu)
            if dengchashu not in sushuList:
                shifoucunzai = False
                break
        if shifoucunzai == True:
            resList.append((val, dengcha))
# 有解的數組
resList.sort(key= lambda x:(-x[1],-x[0]))
# print(resList)
if len(resList)>0:#如果解存在,則在一行中按遞增序輸出等差最大的一組解;若解不唯一,則輸出首數最大的一組解。
    num,cha = resList[0]
    res = [str(num+cha*i) for i in range(n)]
    print(" ".join(res))
else:
    try:
        print(str(sushuList[-1]))
    except:
        print("")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章