Problem 9:

*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.

This one took a few goes to figure out. Initially I’d made a mistake in my loop, which meant I wasn’t getting back any successful results. Then I had a brainwave why this might be (before I realised my mistake): a and b (and even c) could be **negative**!

I then wasted time coming up with a clever nested loop that allowed me to generate all the variations of +/- a, b and c. If I’d just spent some time reading up on natural numbers, I’d have discovered they have to be positive.

When that didn’t give me the results I wanted, I went back to my code, realised my earlier mistake and corrected it (I’d not been incrementing a and b properly).

<cfloop index="a" from="1" to="500">
<cfloop index="b" from="1" to="500">
<cfset pythagoras = (a * a) + (b * b)>
<cfset c = Sqr(pythagoras)>
<cfif c EQ Round(c)>
<!--- it's an integer --->
<cfset sum = a + b + c>
<cfif sum EQ 1000>
<cfset product = a * b * c>
<cfoutput>
#a# + #b# + #c# = #sum#<br>
#a# * #b# * #c# = <strong>#product#</strong>
</cfoutput>
<cfabort>
</cfif>
</cfif>
</cfloop>
</cfloop>

Figure out what a^{2} + b^{2} is. Is it an integer? If so, add a, b and c. Do they add up to 1000? If so, multiply them together, and then stop.

### Like this:

Like Loading...

*Related*

[…] 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 […]

Pingback by Project Euler: problem 9 (PHP) | Duncan's blog — September 27, 2014 @ 8:05 am |