Euler Problem 9

A Pythagorean triplet is a set of three natural numbers, $a < b < c$, for which,

$a^2 + b^2 = c^2$

For example, $3^2 + 4^2 = 9 + 16 = 25 = 5^2$.

There exists exactly one Pythagorean triplet for which $a + b + c = 1000$. Find the product $abc$.

We start bruteforcing even though it feels like there may be a smart solution.

In [1]:
import timeit

def brute_force():
    for a in range(1, 251):
        for b in range(a + 1, 501):
            for c in range(b + 1, 1001):
                if a + b + c == 1000 and a * a + b * b == c * c:
                    return a * b * c

print(timeit.timeit(brute_force, number=10))
print(brute_force())
66.96907186399949
31875000

Let's do some optimization by cancelling the loops when we exceed the boundaries. Actually, I have also realized that choosing 251 and 501 is a little bit arbitrary. For example if a, b, c where something like $332, 333, 335$ that could be a solution and the first range was too low. Then again, we would have realized that as soon as we get back None, so it is okay.

In [2]:
def brute_force():
    for a in range(1, 251):
        for b in range(a + 1, 501):
            if a + b > 600:
                break
            for c in range(b + 1, 1001):
                if a + b + c == 1000 and a * a + b * b == c * c:
                    return a * b * c
                
print(timeit.timeit(brute_force, number=10))
print(brute_force())
64.4656584559998
31875000

Big time save. Kappa. Okay, I am stupid. If I have a and b I can calculate c and check if it is a solution.

In [3]:
def smart_brute_force():
    for a in range(1, 251):
        for b in range(a + 1, 501):
            c = 1000 - a - b
            if a * a + b * b == c * c:
                return a * b * c
       
print(timeit.timeit(smart_brute_force, number=10))
print(smart_brute_force())  
0.22822808900036762
31875000
In [ ]: