fork(1) download
  1. <?php
  2.  
  3. /**
  4.  * Project Euler Problem 4: Largest palindrome product
  5.  *
  6.  * A palindromic number reads the same both ways. The largest palindrome made
  7.  * from the product of two 2-digit numbers is 9009 = 91 × 99.
  8.  *
  9.  * Find the largest palindrome made from the product of two 3-digit numbers.
  10.  *
  11.  * Problem: https://p...content-available-to-author-only...r.net/problem=4
  12.  * Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem004.php
  13.  * Live code: https://i...content-available-to-author-only...e.com/MwUCwn
  14.  */
  15. namespace Potherca\ProjectEuler\Solutions\Problem004
  16. {
  17. use Potherca\ProjectEuler\Calculators\PalindromeProductCalculator as Calculator;
  18.  
  19. $digits = 3;
  20.  
  21. $solution = (new Calculator())->getHighestPalindromeForProduct($digits);
  22.  
  23. echo $solution;
  24. }
  25.  
  26. namespace Potherca\ProjectEuler\Calculators
  27. {
  28. class PalindromeProductCalculator
  29. {
  30. final public function getHighestPalindromeForProduct(int $digits): int
  31. {
  32. $palindromes = $this->getPalindromesForProduct($digits);
  33.  
  34. return end($palindromes);
  35. }
  36.  
  37. final public function getPalindromesForProduct(int $digits): array
  38. {
  39. $low = 10 ** ($digits - 1);
  40. $high = (10 ** $digits) - 1;
  41.  
  42. return $this->getPalindromesForRange($low, $high);
  43. }
  44.  
  45. final public function getPalindromesForRange(int $low, int $high): array
  46. {
  47. $palindromes = [];
  48.  
  49. $numbers = range($low, $high);
  50.  
  51. foreach ($numbers as $left) {
  52. foreach ($numbers as $right) {
  53. $number = $left * $right;
  54.  
  55. $reverse = (int) strrev($number);
  56.  
  57. if (
  58. $reverse === $number
  59. && ! in_array($number, $palindromes)
  60. ) {
  61. $palindromes[] = $number;
  62. }
  63. }
  64. }
  65.  
  66. sort($palindromes);
  67.  
  68. return $palindromes;
  69. }
  70. }
  71. }
  72.  
Success #stdin #stdout 0.11s 24488KB
stdin
Standard input is empty
stdout
906609