projecteuler_problem9

Β 4th April 2024 at 3:13pm

This is an interesting problem that summarizes my interest in Project Euler. There is a clear programmable solution, but the problem is based on a key mathematical concept; and so, a more interesting solution would probably meet halfway between the two (and I'm not yet taking into account efficiency algorithm issues, etc.)

When first working this on paper, I realised there were many possible startpoints: even the question as to check first for either all a+b+c=1000a + b + c = 1000 combinations or manually generate triplets (in fact, a little after starting the problem, one of the initial chapters of GΓΆdel, Escher, Bach lets know that it is possible to generate triplets). But I did indeed lose a lot of time scribbling on paper and getting not much out of it: so I just brute-forced the solution.

for a in range(1, 998):
    for b in range(2, a):
        s = (1000 - a - b)
        if a + b + s == 1000 and a**2 + b**2 == s**2:
            print(a * b * s)

This gives the solution (almost) immediately. And even in bruteforcing, one could make the mistake of iterating once more for the value of cc; it is the difference between creating the necessary value of cc β€” calculating s β€” or looping once more through a range of values to find s. This is quite different: I'm hoping to have conveyed it properly.

There is a first optimisation to be done in the range intervals β€” of course, possible values of aa do not span the entire 1000 range β€” since a<b<ca < b < c, some quick maths show that a≀332a \leq 332, necessarily. Furthermore, bb can also be bound by ss.

The problem's official solution leverages mathematical knowledge on the triples, which is very nice to see.