Project Euler #9
April 20th, 2009

For those who don’t know, Project Euler is “a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve.”, or in other words, “challenging, bite-sized programming tasks”.

If you’ve got the programming itch but don’t want to work on anything that will take very long, these are great.
Here’s my solution to #9, in python.

#!/usr/bin/python
 
# 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.
 
from math import sqrt
from sys import exit
from time import time
 
SUM = 1000
start = time()
 
for b in range(1,SUM + 1):
    for a in range(1, b + 1):
        c = sqrt(a**2 + b**2)
        if a + b + c == SUM:
            print "(%i, %i, %i)" % (a,b,c)
            print "Product = %i" % (a*b*c)
            end = time()
            print "Completed in %f seconds" % (end-start)
            exit()

And the output:

$ python problem9.py
(200, 375, 425)
Product = 31875000
Completed in 0.090962 seconds