fork(1) download
  1. <?php
  2.  
  3. /**
  4.  * Project Euler Problem 1: Multiples of 3 and 5
  5.  *
  6.  * If we list all the natural numbers below 10 that are multiples of 3 or 5, we
  7.  * get 3, 5, 6 and 9. The sum of these multiples is 23.
  8.  *
  9.  * Find the sum of all the multiples of 3 or 5 below 1000.
  10.  *
  11.  * Problem: https://p...content-available-to-author-only...r.net/problem=1
  12.  * Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem001.php
  13.  * Live code: https://i...content-available-to-author-only...e.com/ViI6sA
  14.  */
  15. namespace Potherca\ProjectEuler\Solutions\Problem001
  16. {
  17. use Potherca\ProjectEuler\Calculators\MultiplesCalculator as Calculator;
  18.  
  19. $multiples = [3, 5];
  20. $limit = 1000;
  21.  
  22. $solutions = (new Calculator($multiples))->getSumOfMultiplesBelow($limit);
  23.  
  24. echo $solutions;
  25. }
  26.  
  27. namespace Potherca\ProjectEuler\Calculators
  28. {
  29. class MultiplesCalculator
  30. {
  31. private $multiples;
  32.  
  33. final public function __construct(array $multiples)
  34. {
  35. $this->multiples = array_map(function ($multiple) {
  36. return (int) $multiple;
  37. }, $multiples);
  38. }
  39.  
  40. final public function getMultiplesBelow(int $limit): array
  41. {
  42. $multiples = [];
  43.  
  44. for ($counter = 0 ; $counter < $limit; $counter++) {
  45. if ($this->isMultipleOf($this->multiples, $counter)) {
  46. $multiples[] = $counter;
  47. }
  48. }
  49.  
  50. return $multiples;
  51. }
  52.  
  53. final public function getSumOfMultiplesBelow(int $limit): int
  54. {
  55. return array_sum($this->getMultiplesBelow($limit));
  56. }
  57.  
  58. private function isMultipleOf(array $targets, int $subject): bool
  59. {
  60. return (bool) count(array_filter($targets, function ($target) use ($subject) {
  61. return $subject % $target === 0;
  62. }));
  63. }
  64. }
  65. }
  66.  
Success #stdin #stdout 0.02s 24504KB
stdin
Standard input is empty
stdout
233168