如果p是一个直角三角形的周长,三角形的三边长{a,b,c}都是整数。对于p = 120一共有三组解:
{20,48,52}, {24,45,51}, {30,40,50}
对于1000以下的p中,哪一个能够产生最多的解?
import time
# p推a,b,c
t0 = time.time()
n = 1000
p_num_max = 0
p_max = 1
for p in range(6, n):
p_num = 0
for c in range((p + 3) // 3, p // 2 + 1):
# a < b < c
for b in range((p - c) // 2 + 1, c):
a = p - c - b
if a ** 2 + b ** 2 == c ** 2:
p_num += 1
if p_num > p_num_max:
p_max = p
p_num_max = p_num
print(p_max)
t1 = time.time()
print(t1 - t0)
# a,b,c推p
t0 = time.time()
n = 1000
p_dict = dict()
# 999 >= a + b + c >= a + a + 1 + a + 2
for a in range(1, (n - 4) // 3 + 1):
# 999 >= a + b + c >= a + b + b + 1
for b in range(a + 1, (n - 2 - a) // 1 + 1):
c = pow(a ** 2 + b ** 2, 0.5)
if a + b + c >= n:
break
if c == int(c):
p_dict.setdefault(a + b + c, 0)
p_dict[a + b + c] += 1
if 2 * b + 1 > a ** 2:
break
print(max(p_dict.items(), key=lambda x:x[1]))
t1 = time.time()
print(t1 - t0)