## Posts Tagged ‘prob9’

### Problem 9

June 12, 2009

I didn’t feel right letting the week go by with no solutions posted, so I rigged one up for problem 9 (find the unique Pythagorean triple which sums to 1000). To generate Pythagorean triples, I used what is identified as Euclid’s Formula on the Wikipedia page for Pythagorean triples. After a little while, I decided the appropriate generalization of this problem was to take in any number, and find all of the Pythagorean triples that sum to the given number. Here’s what I came up with:

```import sys
goal = len(sys.argv) >= 2 and int(sys.argv[1]) or 1000

for n in xrange(1,goal):
for m in xrange(n+1,goal,2):
a,b = 2*m*n,m*m-n*n
trip = (min(a,b),max(a,b),m*m+n*n)
s = sum(trip)
if(goal % s == 0):
k = goal // s
trip = map(lambda x:k*x,trip)
I’m fairly certain that the loops could be cut down in size, but I’m a bit tired right now to see exactly how far. I increment $m$ by 2 because it keeps the parity of $m$ and $n$ different, which Wikipedia claims is a requirement to generate a “primitive” triple.