This article is part of my #100DaysOfCode and #100DaysOfBlogging challenge. R1D13


In the meanwhile, dstockto reviewed and approved my solution. 🤘🏼 Funny story: He found my blog and saw my submission here before seeing it on Exercism.

He gave me an interesting additional challenge, to use “closed” form math-based solutions. This would also allow performance improvement, since the current implementation will take longer the larger $number is.

Square Of Sum

For this function dstockto mentioned the Gauss formula. This is a form to sum the first n positive integers.


function squareOfSum(int $number) : int
{
    $sum = ($number * $number + $number) / 2;
    return $sum \* \$sum;
}

Sum Of Squares

Now researching for a form to sum squares, I come across a wiki page on Brillant. Under the paragraph Sum of the Squares of the First n Positive Integers I find what I am looking for. Read the linked article, if you’re interested in more.

This is the refactored function:

function sumOfSquares(int $number) : int
{
    return ($number * ($number + 1) * (2 * $number + 1)) / 6;
}

Completed

The tests are all green and I am very happy to have taken the additional challenge. In my first solution, I made usage of PHP standard functions only. Now with a mathematical approach, the code became much more readable.