project-euler/142_perfect_square_collecti...

42 lines
897 B
Python
Raw Normal View History

2023-03-26 17:21:44 +02:00
#!/usr/bin/env python3
from math import sqrt
from itertools import combinations
def is_square(n):
return int(sqrt(n))**2 == n
zbound = 10**6
zs = [[] for i in range(zbound)]
c = 1
while c - 2 < len(zs):
d = c-2
while d > 0 and (c**2 - d**2) // 2 < len(zs):
zs[(c**2 - d**2) // 2].append((c**2 + d**2) // 2)
d -= 2
c += 1
max_z = None
min_sum = None
for z in range(1, len(zs)):
if max_z != None and z > max_z:
#print("found")
break
nums = sorted(zs[z])[::-1]
if len(nums) < 2:
continue
for cd, ef in combinations(nums, 2):
if is_square(cd + ef) and is_square(cd - ef):
x = cd
y = ef
#print(x, y, z)
if min_sum == None or min_sum > x + y + z:
min_sum = x + y + z
if max_z == None or x < max_z:
max_z = x
print(min_sum)