Skip to content

Instantly share code, notes, and snippets.

@derrekbertrand
Created October 21, 2017 20:03
Show Gist options
  • Save derrekbertrand/7fbeec18f8a75286ce7c0d17b026185d to your computer and use it in GitHub Desktop.
Save derrekbertrand/7fbeec18f8a75286ce7c0d17b026185d to your computer and use it in GitHub Desktop.
<?php
/*
The methods are in the order worked on:
First, what is a palindrome? How can tell if something `is_palindromic`?
Generate numbers with N `digits`. Abuse the fact that
intval('non numeric string') == 0
Generate all `products` of numbers with N `digits`.
Given `products` of numbers with N `digits`, find the largest palindrome
among them.
I then used the known sets below it to test the validity of each part,
so I can induce it is accurate for any positive integer (including 3).
I can also induce that it gets super slow after 4, and there's probably
a faster algorithm.
*/
class Palindrome
{
/**
* Is a given integer palindromic?
*
* @param integer $number
* @return boolean
*/
public static function is_palindromic(int $number)
{
// all single digit numbers are palindromic
if($number < 10)
return true;
$number = strval($number);
$length = strlen($number);
$length = intdiv($length, 2);
// at this point, $number is a string and $length is the number of digits we care about
$front = substr($number, 0, $length);
$back = strrev(substr($number, -$length));
return !strcmp($front, $back);
}
/**
* Generate all integers of a given 'size', which is the number of digits it has.
*
* @param integer $size
* @return Iterator
*/
public static function digits(int $size)
{
if($size < 1) {
throw new Exception('You cannot generate numbers with '.$size.' digits.');
}
$max_number = intval(str_repeat('9', $size));
$min_number = intval(str_repeat('9', $size-1)) + 1;
for($i = $min_number; $i <= $max_number; $i++)
yield $i;
}
/**
* Take all integers of a given 'size', and return their poducts.
*
* @param integer $size
* @return Iterator
*/
public static function products(int $size)
{
foreach(static::digits($size) as $n)
foreach(static::digits($size) as $m)
yield $n*$m;
}
/**
* If we took all integers of a given 'size' and multiplied them together, what is the biggest palindrome produced?
*
* @param integer $size
* @return integer
*/
public static function largestProductOfDigit(int $size)
{
$max = 0;
foreach(static::products($size) as $n) {
if(static::is_palindromic($n))
$max = max($max, $n);
}
return $max;
}
}
echo 'The largest: '.Palindrome::largestProductOfDigit(3)."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment