fork(1) download
  1. <?php
  2.  
  3. /**
  4.  * Project Euler Problem 6: Sum square difference
  5.  *
  6.  * The sum of the squares of the first ten natural numbers is,
  7.  *
  8.  * 1² + 2² + ... + 10² = 385
  9.  *
  10.  * The square of the sum of the first ten natural numbers is,
  11.  *
  12.  * (1 + 2 + ... + 10)² = 55² = 3025
  13.  *
  14.  * Hence the difference between the sum of the squares of the first ten natural
  15.  * numbers and the square of the sum is 3025 − 385 = 2640.
  16.  *
  17.  * Find the difference between the sum of the squares of the first one hundred
  18.  * natural numbers and the square of the sum.
  19.  *
  20.  * Problem: https://p...content-available-to-author-only...r.net/problem=6
  21.  * Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem006.php
  22.  * Live code: https://i...content-available-to-author-only...e.com/zgflJ5
  23.  */
  24. namespace Potherca\ProjectEuler\Solutions\Problem006
  25. {
  26. use Potherca\ProjectEuler\Calculators\SumSquareDifferenceCalculator as Calculator;
  27.  
  28. $limit = 100;
  29.  
  30. $solution = (new Calculator())->getSumSquareDifference($limit);
  31.  
  32. echo $solution;
  33. }
  34.  
  35. namespace Potherca\ProjectEuler\Calculators
  36. {
  37. class SumSquareDifferenceCalculator
  38. {
  39. final public function getSumSquareDifference(int $limit): int
  40. {
  41. $range = range(1, $limit);
  42.  
  43. return $this->getSquareOfSums($range) - $this->getSumOfSquares($range);
  44. }
  45.  
  46. private function getSquareOfSums(array $range): int
  47. {
  48. return array_sum($range) ** 2;
  49. }
  50.  
  51. private function getSumOfSquares(array $range): int
  52. {
  53. return array_sum(
  54. array_map(function ($number) {
  55. return $number ** 2;
  56. }, $range)
  57. );
  58. }
  59. }
  60. }
  61.  
Success #stdin #stdout 0.01s 24548KB
stdin
Standard input is empty
stdout
25164150