Project Euler Problem 142

# Statement

Find the smallest x + y + z with integers x > y > z > 0 such that x + y, x y, x + z, x z, y + z, y z are all perfect squares.

# Solution

In order to solve this problem, first, we have to express the different equations and then start working with them.

Let's begin expressing the equations:

$x + y = A$

$x - y = B$

$x + z = C$

$x - z = D$

$y + z = E$

$y - z = F$

Now let's begin working with them, we can express:

$x - z = (x + y) - (y + z) \rightarrow D = A - E$

$x + z = (x + y) - (y - z) \rightarrow C = A - F$

$x - y = (x + z) - (y + z) \rightarrow B = C - E$

So, bruteforcing only the values we can obtain possible solutions, but in order to get the values of x, y z we need to solve the linear equation:

$x - z = D$

$x + z = C$

$x - y = B$

which has only one solution, this one:

$x = \frac {D + C} {2}$

$y = -\frac{(2B -D - C)} {2}$

$z = -\frac{D - C} {2}$

From this solution we can see that D+C must be even, so D and C must have the same parity, thus E and F must have the same parity.

from itertools import count, takewhile

is_square = lambda x: int(x ** 0.5) ** 2 == x

if __name__ == '__main__':
for a in count(6):
a_2 = a ** 2
for f in (f for f in takewhile(lambda f: f < a, count(4)) if is_square(a_2 - f ** 2)):
f_2 = f ** 2
c_2 = a_2 - f_2
setoff = 3 if (f & 1) else 2
for e in (e for e in takewhile(lambda e: e ** 2 < c_2, count(setoff, 2)) if is_square(c_2 - e ** 2) and is_square(a_2 - e ** 2)):
e_2 = e ** 2
b_2 = c_2 - e_2
d_2 = a_2 - e_2
z = -(d_2 - c_2) // 2
y = -(-d_2 - c_2 + 2 * b_2) // 2
x = (d_2 + c_2) // 2
print('The result is: (x){0} + (y){1} + (z){2} = {3}'.format(x, y, z, x + y + z))
exit(0)