fork(1) download
  1. <?php
  2.  
  3. /**
  4.  * Project Euler Problem 2: Even Fibonacci numbers
  5.  *
  6.  * Each new term in the Fibonacci sequence is generated by adding the previous
  7.  * two terms. By starting with 1 and 2, the first 10 terms will be:
  8.  *
  9.  * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  10.  *
  11.  * The sum of the even-valued terms whose values do not exceed one hundred would
  12.  * be 44 (2 + 8 + 34)
  13.  *
  14.  * By considering the terms in the Fibonacci sequence whose values do not exceed
  15.  * four million, find the sum of the even-valued terms.
  16.  *
  17.  * Problem: https://p...content-available-to-author-only...r.net/problem=2
  18.  * Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem002.php
  19.  * Live code: https://i...content-available-to-author-only...e.com/Sur5V4
  20.  */
  21. namespace Potherca\ProjectEuler\Solutions\Problem002
  22. {
  23. use Potherca\ProjectEuler\Calculators\FibonacciCalculator as Calculator;
  24.  
  25. $limit = 4000000;
  26.  
  27. $solution = (new Calculator())->getSumOfEvenTermsBelow($limit);
  28.  
  29. echo $solution;
  30. }
  31.  
  32. namespace Potherca\ProjectEuler\Calculators
  33. {
  34. class FibonacciCalculator
  35. {
  36. final public function getSumOfEvenTermsBelow(int $limit): int
  37. {
  38. return array_sum($this->getEvenTermsBelow($limit));
  39. }
  40.  
  41. final public function getEvenTermsBelow(int $limit): array
  42. {
  43. return array_filter($this->getTermsBelow($limit), function ($term) {
  44. return $term % 2 === 0;
  45. });
  46. }
  47.  
  48. final public function getTermsBelow(int $limit): array
  49. {
  50. $terms = [];
  51.  
  52. $previousTerm = 0;
  53. $currentTerm = 1;
  54.  
  55. while ($previousTerm + $currentTerm < $limit) {
  56. $term = $previousTerm + $currentTerm;
  57.  
  58. $terms[] = $term;
  59.  
  60. $previousTerm = $currentTerm;
  61. $currentTerm = $term;
  62. };
  63.  
  64. return $terms;
  65. }
  66. }
  67. }
  68.  
Success #stdin #stdout 0.02s 24212KB
stdin
Standard input is empty
stdout
4613732