Duncan's blog

October 27, 2008

Project Euler: problem 9

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.

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>
				#a# + #b# + #c# = #sum#<br>
				#a# * #b# * #c# = <strong>#product#</strong>

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.


1 Comment »

  1. […] 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 | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: