Duncan's blog

September 24, 2014

Project Euler: problem 6 (PHP) – Sum square difference

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

SixI 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 6:

The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 – 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Code:

<?php
$sum1 = 0;
$sum2 = 0;

for ($i = 1; $i <= 100; $i++) {
	$sum1 += ($i * $i);
	$sum2 += $i;
}

$sum2 *= $sum2;

$difference = $sum2 - $sum1;

echo "sum1: " . $sum1 . "<br>";
echo "sum2: " . $sum2 . "<br>";
echo "difference: " . $difference . "<br>";

I wanted to do $i squared using an exponentiation operator.  In ColdFusion you do x ^ 2, but that does a bitwise XOR in PHP.  Instead you use x ** 2.  However this was only introduced in PHP 5.6, which wasn’t released until  about 3 weeks ago! I’m currently running 5.5 so didn’t have access to that.  By contrast ColdFusion has had an exponentiation operator since at least 4.5 (released 1999), and I suspect it’s been in there since version 1 or 2.

So instead you can simply do $i * $i as I’ve done here, or I could also have used the pow() function.  If I was doing anything more complex than squaring it, that’s what I’d have done obviously.

Leave a Comment »

No comments yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: