// you’re reading...

Project Euler Solutions

Project Euler Problem 9 Solution

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Problem Description

A Pythagorean triplet is a set of three natural numbers, ab < c, for which,

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.

Analysis

This site provided a simple formula for generating Pythagorean triplets. Here’s the formula:
Suppose that m and n are two positive integers, with m < n.
Then n2m2, 2mn, and n2 + m2 is a Pythagorean triple.

Ok, let’s work this out:
(n2 -m2) + 2mn + (n2 + m2) = 1000
2n2 + 2mn = 1000
2n(n+m) = 1000
n(n+m) = 500
for m=20, a
n2 + mn = 500

So, to find the maximum n, such that m < n, we search downwards and return the first one found. An assumption for this method is that the gcd(a, b, c) = 1. This simply means that a, b and c need to be reduced to their lowest terms. For example, {6, 8, 10} is a Pythagorean triple, but can be reduced to {3, 4, 5}.

Solution

Runs < 1 second in Python.

def pe9(p):
  LL = int(p**.5)
  for i in range(1, LL, 2):
    for j in range(2, LL, 2):
        a = abs(j*j - i*i)
        b = 2*i*j;
        c = i*i + j*j
        if a+b+c == p:
           return a*b*c
print "Answer to PE9 = ",pe9(1000)

Comments

Discussion

One comment for “Project Euler Problem 9 Solution”

  1. [...] is an extension to the Problem 9 [...]

    Posted by Dreamshire | Project Euler Problem 75 Solution | July 9, 2009, 1:02 pm

Post a comment