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

*The sum of the squares of the first ten natural numbers is,*

1^{2} + 2^{2} + … + 10^{2} = 385

*The square of the sum of the first ten natural numbers is,*

(1 + 2 + … + 10)^{2} = 55^{2} = 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.

### Like this:

Like Loading...

*Related*

## Leave a Reply