Project Euler: Problem 9

This is Problem 9 on Project Euler:

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.

Pythagorean triplets can be generated by using the following formulas, where m and n are integers and m is greater than n:

m^(2) – n^(2)
2mn
m^(2) + n^(2)

So for the purposes of this problem we are looking for values for m and n where these three formulas add up to 1000, that is:

(m^(2) – n^(2)) + (2mn) + (m^(2) + n^(2)) = 1000
This can be simplified to 2m^(2) + 2mn = 1000
Dividing by 2 and factoring by m we have m(m+n) = 500
Therefore m must be a factor of 500. Calculating m, m + n and n we get the following table:

mm + nnnotes
1500499Reject, because n is greater than m
2250248Reject, because n is greater than m
510095Reject, because n is greater than m
105040Reject, because n is greater than m
20255A solution
2520-5Reject, because n cannot be negative
5010-40Reject, because n cannot be negative
1005-95Reject, because n cannot be negative
2502-248Reject, because n cannot be negative
5001-499Reject, because n cannot be negative

Therefore the only solution is where m = 20 and n = 5. Plugging these values into our original expressions we have:

a = m^(2) – n^(2) = (20 * 20) – (5 * 5) = 375

b = 2mn = 2 * 20 * 5 = 200

c = m^(2) + n^(2) = (20 * 20) + (5 * 5) = 425

a + b + c = 1000 and ^(2) + b^(2) = c^(2), so the answer to the problem is a * b * c.

We have not had to use a computer to solve this problem, but a brute-force approach in Delphi could be this:

procedure TfrmMain.Problem9;
var
	a, b, c : integer;
begin
	for a := 1 to 998 do begin
		for b := a + 1 to 999 do begin
			c := 1000 - (a + b);
			if (a * a) + (b * b) = (c * c) then begin
				ShowMessage(IntToStr(a * b * c));
				exit;
			end;
		end;
	end;
end;

This code just generates sets of numbers where a + b + c = 1000 and then checks the set for being a Pythagorean triple. If it is, the product is displayed. There are no optimizations in this code, which could be improved considerably.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *