任意一个偶数(大于2)都可以由2个素数组成,组成偶数的2个素数有很多种情况,本题目要求输出组成指定偶数的两个素数差值最小的素数对。
数据范围:输入的数据满足 4≤n≤1000
输入一个大于2的偶数
从小到大输出两个素数
输入:
20
复制输出:
7 13
复制
输入:
4
复制输出:
2 2
思路一:硬编码,双指针
import math
while True:
try:
n = int(input())
l = [
p
for p in range(2, n)
if 0 not in [p % d for d in range(2, int(math.sqrt(p)) + 1)]
]
# ll = []
# for i in range(2,n):
# lll = []
# for j in range(2,int(sqrt(i))+1):
# lll.append(i%j)
# if 0 not in lll:
# ll.append(i)
start_index = 0
end_index = -1
ret = []
for i in range(len(l)):
if l[start_index] * 2 == n:
ret.append((l[start_index], l[start_index]))
break
elif l[end_index] * 2 == n:
ret.append((l[end_index], l[end_index]))
break
elif l[start_index] >= l[end_index]:
break
elif l[start_index] + l[end_index] > n:
end_index += -1
elif l[start_index] + l[end_index] < n:
start_index += 1
elif l[start_index] + l[end_index] == n:
ret.append((l[start_index], l[end_index]))
end_index += -1
start_index += 1
for i in ret[-1]:
print(i)
except:
break
思路二,利用i + n - i =n为条件遍历
def isSuShu(x):
if x <= 2:
return True
else:
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
else:
return True
while True:
try:
n = int(input())
for i in range(int(n / 2), n):
if isSuShu(i) and isSuShu(n - i):
print(n - i)
print(i)
break
except:
break