# Duncan's blog

## September 27, 2014

### Project Euler: problem 9 (PHP) – Special Pythagorean triplet

Filed under: PHP,Project Euler — duncan @ 8:00 am

Photo courtesy of nan

I previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 9:

A Pythagorean triplet is a set of three natural numbers, a < b < 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.

Code:

```<?php
for (\$a = 1; \$a <= 500; \$a++) {
for (\$b = 1; \$b <= 500; \$b++) {
\$pythagoras = (\$a * \$a) + (\$b * \$b);
\$c = sqrt(\$pythagoras);

if (\$c == intval(\$c)) {
\$sum = \$a + \$b + \$c;

if (\$sum == 1000) {
\$product = \$a * \$b * \$c;

echo \$a . " + " . \$b . " + " . \$c . " = " . \$sum . "<br>";
echo \$a . " * " . \$b . " * " . \$c . " = " . \$product . "<br>";
break 2;
}
}
}
}
```

Very similar code to my ColdFusion version.  Previously I used round() to do a comparison and see if my value was an integer.  I thought it would be more appropriate and simpler to just use PHP’s is_int() function, except it didn’t seem to work, I think due to the larger numbers being used.  So I used intval() instead to do a similar comparison as before.

Also I’m specifying break 2 to break out of the parent loop, otherwise break on its own just breaks out of the inner-most loop and we keep running and end up getting the same factors again in a different combination.  What would be nice would be some way to specify break out of the parent loop, without having to know exactly how many loops that is.  My code here is simple enough it’s easy to see there’s only 2 loops, therefore break 2.  However if you’re writing anything complicated with many nested loops it’s not always so obvious.