The Home for People Who Like to Flip Out and Write Code
Project Euler: Problem 9
Problem 9 deals with one of the more interesting
things I learned in high school geometry:
Pythagorean triples. In high school, I just
memorized the 2 most common ones (3, 4, 5 and 5, 12, 13) and thought to
myself: Wouldn’t it be cool if I could generate all of these? But that
was in the before time; Wikipedia didn’t exist and my text book wasn’t
cool enough to dwell on them. At any rate, now I know Euclid’s formula
for generating Pythagorean triples:
Here’s the script I used to solve the actual problem:
12345678910111213141516171819202122232425
"""Solves Problem 9 from Project Euler."""importoperatordeftriples(upper_bound):"""Generator for Pythagorean Triples (represented as tuples). Uses Euclid's formula to generate Pythagorean Triples (see http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple). """forminxrange(2,upper_bound):forninxrange(1,m):yieldm**2-n**2,2*m*n,m**2+n**2# Only uncomment if the triples we get from the original Euclid's are insufficient.# for k in xrange(1, upper_bound):# yield k * (m ** 2 - n ** 2), k * (2 * m * n), k * (m ** 2 + n ** 2)defproblem_9():"""Finds the product of the Pythagorean Triple where a + b + c = 1000."""fortripleintriples(1000):ifsum(triple)==1000:returnreduce(operator.mul,triple)return0if__name__=='__main__':printproblem_9()