Problem: Find the difference between the sum of the square of the first 100 natural numbers, and the square of the sum of the first 100 natural numbers.
Solution: PHP has three functions which are useful here:
- range: Creates an array of elements between start and end points (e.g. 1 and 100).
- array_sum: Returns the sum of all the elements in an array.
- array_map: Calls a function on every element of an array.
We use range
to generate an array of numbers, array_sum
to find the sum and square it, and array_map
to find the squares and then array_sum
to sum them.
<?php declare(strict_types=1); error_reporting(E_ALL); $numbers = range(1, 100); $square_of_sum = array_sum($numbers) ** 2; $sum_of_squares = array_sum(array_map(function($n) { return $n ** 2; }, $numbers)); $diff = abs($square_of_sum - $sum_of_squares); print("$diff\n");