新人回陈贴,希望没违规。
跑了5s多,但比最初的780多秒还是要好多了。import time
t0 = time.time()
def iscoprime(b, a): # 检查互质
yushu = b % a
while yushu != 0:
b = a
a = yushu
yushu = b % a
if a == 1:
return True
else:
return False
MAXC = 120000
rad = [0]*MAXC
rad[1] = 1
for i in range(2, MAXC): # 先计算rad值
if rad[i] > 0:
continue
for j in range(i, MAXC, i):
if rad[j] == 0:
rad[j] = i
else:
rad[j] *= i
DicRADN = {}
countc, sumc = 0, 0
for i in range(1, MAXC): # 以rad值为key,原数字为value,生成字典
try:
DicRADN[rad[i]].append(i)
except KeyError:
DicRADN[rad[i]] = [i]
for c in range(3, MAXC):
maxradab = c//rad[c] # rad(a)*rad(b)的最大值
if maxradab == 1: # 这种情况只能是rada=radb=1,即a=b=1,不合题意
continue
for rada in DicRADN.keys():
if rada > maxradab//2: # 因为b一定至少有一个质因子是2次方以上,所以radb≥2
break
for a in DicRADN[rada]:
if a > (c-1)//2: # 因为a<b,所以a<c/2
break
b = c-a
if rad[b] == b: # b为质数的一次方的乘积。易证不合题意。
continue
if rad[a]*rad[b] >= maxradab:
continue
if iscoprime(b, a):
countc += 1
sumc += c
print("Answer: [数量, 求和]:", countc, sumc)
print("Start time: ", time.asctime(time.localtime(t0)))
print("Running time: ", time.time()-t0, "s")
Answer: [数量, 求和]: 456 18407904
Running time: 5.613126516342163 s |