// you’re reading...

Project Euler Solutions

Project Euler Problem 39 Solution

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

Problem Description

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p ≤ 1000, is the number of solutions maximised?

Analysis

The Pythagorean Theorem gives us: a2 + b2 = c2 and by intuition a + b + c = p (perimeter).
The decision to iterate perimeters has many advantages over generating right triangles. Only even numbered perimeters need to be checked; below is our analysis:

Independent Dependent
a b c p
E E E E
O O E E
E O O E
O E E E

No matter which integral values we choose for a, b and c such that a2 + b2 = c2 the perimeter will be even.

By iterating perimeters we need a method to check for integral (integer) right triangles.
We can interpret the Pythagorean theorem as a2 + b2 = (p-a-b)2 since c = p-a-b. After expanding and simplifying we have:
b = p(p – 2a) / 2(p-a) and when this equation evaluates to an integer (MOD(p(p – 2a), 2(p-a)) = 0) we have our triangle.

One last optimization. By using a+b>c and symmetry we only need to investigate values of a to p/4.

Solution

Runs < 1 second in Python.

t_max = 0;
p_limit = 1000
 
for p in xrange (2, p_limit+1, 2):
  t = 0;
  for a in xrange (2, p/4+1):
    if  p*(p - 2*a) % (2*(p-a)) == 0: t += 1
    if t > t_max: (t_max, p_max) = (t, p)
 
print "Answer to PE30 = ", p_max

Comments

Some other results:
10,000 = 9,240
100,000 = 55,440
1,000,000 = 720,720
10,000,000 = 6,126,120

Discussion

No comments for “Project Euler Problem 39 Solution”

Post a comment