Created
March 21, 2019 22:05
-
-
Save bert-w/268e13da12a4e9340a23e325998408ea to your computer and use it in GitHub Desktop.
Find a high multiplicative persistence in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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