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.
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 a2 + b2 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.