题目
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("")