A Pythagorean triplet is a set of three natural numbers, $a
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$.
This is a fairly straighforward constraint satisfaction problem (CSP) and is perhaps most easily solved in a CSP modelling language such as MiniZinc. However, to employ such tools would be to defeat the very purpose of the exercise, which is to give us practice with implementation.
from six.moves import range, reduce
pair_sum_eq = lambda n, start=0: ((i, n-i) for i in range(start, (n>>1)+1))
[(5, 16), (6, 15), (7, 14), (8, 13), (9, 12), (10, 11)]
Note that $3a pair_sum_eq. Within the innermost loop, the $a, b, c$ now satisfy the constraints $a
def pythagorean_triplet_sum_eq(n): for a in range(1, n//3+1): for b, c in pair_sum_eq(n-a, start=n//3): if a*a + b*b == c*c: yield a, b, c
[(200, 375, 425)]
prod = lambda iterable: reduce(lambda x,y: x*y, iterable)
(200, 375, 425)