Skip to content

Instantly share code, notes, and snippets.

@roniemicro
Created May 1, 2013 12:43
Show Gist options
  • Save roniemicro/5495090 to your computer and use it in GitHub Desktop.
Save roniemicro/5495090 to your computer and use it in GitHub Desktop.
3n+1 Php Implementation
<?php
ini_set('xdebug.max_nesting_level', 10000000);
function isOdd($n)
{
return ($n & 1);
}
function getStepCount($number, &$cache)
{
$count = 1;
$n = $number;
while ( $n > 1 ) {
if ( isset($cache[$n]) ) {
$count = $count + $cache[$n] - 1;
break;
}
$count++;
if ( isOdd($n) ) {
$n = 3 * $n + 1;
} else {
$n = $n / 2;
}
}
$cache[$number] = $count;
return $count;
}
function evaluateAlgorithm($n, &$cache)
{
if ( isset($cache[$n]) ) {
return $cache[$n];
}
if ( $n <= 1 ) {
$count = 0;
} elseif ( isOdd($n) ) {
$count = evaluateAlgorithm(3 * $n + 1, $cache);
} else {
$count = evaluateAlgorithm($n / 2, $cache);
}
return $cache[$n] = $count + 1;
}
function getValidInput($argc, $argv)
{
$n = array();
switch ( $argc ):
case 3 :
$n = array($argv[1], $argv[2]);
break;
case 2 :
$n = explode(",", $argv[1]);
break;
default :
endswitch;
if ( count($n) == 2 && $n[0] <= $n[1] && $n[0] > 0 && $n[1] < 1000000 ) {
return $n;
}
die("Invalid Input" . PHP_EOL);
}
function getMaximumStep($i, $j, &$cache, $stepCounter = 'getStepCount')
{
if ( $i > $j ) {
return "Wrong Input";
}
$data = array(
'max_step' => 0,
'max_step_n' => FALSE
);
for ($n = $i; $n <= $j; $n++) {
$current_steps = $stepCounter($n, $cache);
if ( $current_steps > $data['max_step'] ) {
$data['max_step'] = $current_steps;
$data['max_step_n'] = $n;
}
}
return "Maximum Step (" . $data['max_step'] . ") Needed for number : " . $data['max_step_n'];
}
$cache = array();
$cache1 = array();
$n = getValidInput($argc, $argv);
echo PHP_EOL . "======= Using Loop ========" . PHP_EOL;
$eStart = microtime(TRUE);
echo getMaximumStep($n[0], $n[1], $cache) . PHP_EOL;
$eEnd = microtime(TRUE);
echo 'Execution time: ' . ($eEnd - $eStart) * 1000 . ' ms' . PHP_EOL;
echo PHP_EOL . "======= Using Recursion ========" . PHP_EOL;
$eStart = microtime(TRUE);
echo getMaximumStep($n[0], $n[1], $cache1, 'evaluateAlgorithm') . PHP_EOL;
$eEnd = microtime(TRUE);
echo 'Execution time: ' . ($eEnd - $eStart) * 1000 . ' ms' . PHP_EOL;
echo PHP_EOL . "======= Using Recursion Again ========" . PHP_EOL;
$eStart = microtime(TRUE);
echo getMaximumStep($n[0], $n[1], $cache1, 'evaluateAlgorithm') . PHP_EOL;
$eEnd = microtime(TRUE);
echo 'Execution time: ' . ($eEnd - $eStart) * 1000 . ' ms' . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment