Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.
The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.
Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.
Go to the root of your PHP exercise directory, which is <EXERCISM_WORKSPACE>/php
.
To find the Exercism workspace run
% exercism debug | grep Workspace
Get PHPUnit if you don't have it already.
% wget --no-check-certificate https://phar.phpunit.de/phpunit.phar
% chmod +x phpunit.phar
Execute the tests:
% ./phpunit.phar difference-of-squares/difference-of-squares_test.php
Problem 6 at Project Euler http://projecteuler.net/problem=6
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
<?php
require_once "difference-of-squares.php";
class SquaresTest extends PHPUnit\Framework\TestCase
{
public function testSquareOfSumTo5()
{
$this->assertEquals(225, squareOfSum(5));
}
public function testSumOfSquaresTo5()
{
$this->assertEquals(55, sumOfSquares(5));
}
public function testDifferenceOfSumTo5()
{
$this->assertEquals(170, difference(5));
}
public function testSquareOfSumTo10()
{
$this->assertEquals(3025, squareOfSum(10));
}
public function testSumOfSquaresTo10()
{
$this->assertEquals(385, sumOfSquares(10));
}
public function testDifferenceOfSumTo10()
{
$this->assertEquals(2640, difference(10));
}
public function testSquareOfSumTo100()
{
$this->assertEquals(25502500, squareOfSum(100));
}
public function testSumOfSquaresTo100()
{
$this->assertEquals(338350, sumOfSquares(100));
}
public function testDifferenceOfSumTo100()
{
$this->assertEquals(25164150, difference(100));
}
}
<?php
function squareOfSums($num) {
return array_sum(range(1, $num)) ** 2;
}
function sumOfSquares($num) {
return array_sum(array_map(square, range(1, $num)));
}
function difference($num) {
return squareOfSums($num) - sumOfSquares($num);
}
function square($num) {
return $num ** 2;
}
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Community comments
I didn't know about array_sum! thanks!