简单粗暴直接解: 先求素表,再寻找和等于目标值的素数对,记录最小差。
while True:
try:
N = int(input())
min_delta = N
min_i = 0
prime_l = [True for i in range(N+1)]
prime_l[0] = False
prime_l[1] = False
#用筛数法求出N以内的素数列表:素数表的快速求解还有很多优化的方法,如减小循环的范围,减小内循环的重复判断
#通过全部用例,运行时间,57ms,占用内存,7012KB
'''
for i in range(2, N+1):
if prime_l[i] != False:
for j in range(2*i, N+1, i):
prime_l[j] = False
'''
#优化了,好像测试用例的时间体现不出来变化。通过全部用例,运行时间,64ms,占用内存,7104KB
i = 2
while(i*i < N+1):
if prime_l[i] != False:
for j in range(i*i, N+1, i): #从i*i 起始,而不再是线性地从i+i开始
prime_l[j] = False
i += 1
for i in range(2, int(N/2)+1): #只需要搜索到一半即可,一半的写法int(N/2)+1, 要注意加1包含一半本身
if (prime_l[i] == True) and (prime_l[N-i] == True): #判断N分解成的两个和数的是否都为素数
if (abs(N-i-i) < min_delta):#判断差值是否更小,是则更新最小值记录
min_delta = abs(N-i-i)
min_i = i
print(min_i)
print(N-min_i)
except:
break