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.
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())
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.
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())
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.
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())