2011-12-27

# Project Euler problem 142 - Solved

The statement of the problem can be found here.

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:

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

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:

which has only one solution, this one:

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.

With all this in mind we can easily write an algorithm in Python to solve the problem (problem142.py):

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)