Skip to content

PE 0009: Special Pythagorean Triplet

A Pythagorean triplet is a set of three numbers a,b,cN, a<b<c and

a2+b2=c2

For example, 32+42=9+16=25=52.

There exists exactly one Pythagorean triplet for which a+b+c=1000.

Find the product abc.


We are given two constraints to find three variables but we know the search space is bounded and reasonably small. We're searching for two numbers (a, b) which together must sum less than 1000 because a third must add with them to 1000 and we know all three numbers are greater than zero.

Since we can derive c from the a,b pair, we're really looking at 1000×1000 (at most), or less than one million possibilities. Really not that much, so it's reasonable to use brute-force search:

python
for a in range(2, number):
  for b in range(a+1, number):
    c = number - a - b
    c2 = a**2 + b**2
    if c**2 == c2:
      PythagoreanTriplet(a, b, c)

We can avoid any floating-point math by comparing c2 instead of taking the root of one to compare them as c. This avoids having to check for "equal within a tolerance". We can also start the b value at one more than a because a Pythagorean triplet has unique values by definition (also, if a=b then we know c cannot be in N, do you see why?).

See Also

TODO

Exercises

TODO