Skip to content

Instantly share code, notes, and snippets.

@bert-w
Created March 21, 2019 22:05
Embed
What would you like to do?
Find a high multiplicative persistence in PHP
<?php
// INPUT VARS
$start = 2677889;
$end = 26888999;
/**
* @param integer $input
* @return false|int
*/
function search($input)
{
$str = (string)$input;
$loop = $str[0];
$strlen = strlen($str);
for ($i = 1; $i < $strlen; $i++) {
// Check for:
// - Non-increasing digits left to right
// - Zero's
// - Adjacent digits less than 10 when multiplied (*24*579 is simplified to 57*8*9)
if ($str[$i] < $loop || $str[$i] === '0' || ($i + 1 < $strlen && $str[$i] * $str[$i + 1] <= 10)) {
return false;
}
$loop = $str[$i];
}
return check($str);
}
/**
* @param string $str
* @param int $step
* @return int
*/
function check($str, $step = 0)
{
$total = 1;
for ($i = 0; $i < strlen($str); $i++) {
$total *= $str[$i];
}
$step++;
if (strlen($total) === 1) {
return $step;
}
return check((string)$total, $step);
}
$results = [];
for ($i = $start; $i <= $end; $i++) {
$result = search($i);
if (!$result) {
continue;
}
if (!array_key_exists($result, $results)) {
$results[$result] = $i;
} else {
if ($results[$result] > $i) {
$results[$result] = $i;
}
}
}
foreach ($results as $count => $number) {
echo $count . ' => ' . $number . '<br />';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment