Created
April 12, 2016 16:41
-
-
Save timbotron/e72b34d33ffc1a45101853b442521300 to your computer and use it in GitHub Desktop.
Collatz Solve
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 | |
/* | |
The following iterative sequence is defined for the set of positive integers: | |
n → n / 2 (n is even) | |
n → 3n + 1 (n is odd) | |
Using the rule above and starting with 13, we generate the following sequence: | |
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 | |
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1 (and for this interview you may assume this is correct). | |
Which starting number, under one million, produces the longest chain? | |
*/ | |
// TIMH Solution VV | |
function collatz_calc($starting_num,$all_vals) { | |
$chain_len = 0; | |
$current_val = $starting_num; | |
while($current_val != 1) { | |
// Do we already know the rest? | |
if(isset($all_vals[$current_val])) { | |
return $chain_len + $all_vals[$current_val]; | |
} | |
if(($current_val % 2) == 0) { | |
// even case | |
$current_val = (int)($current_val / 2); | |
$chain_len++; | |
} else { | |
// Odd case | |
$current_val = (int)($current_val * 3 + 1); | |
$chain_len++; | |
} | |
} | |
$chain_len++; | |
return $chain_len; | |
} | |
$max_val = ['val'=>1,'chain_len'=>1]; | |
$all_vals = []; | |
for ( $i = 2; $i < 1000000; $i++) { | |
$current_len = collatz_calc($i,$all_vals); | |
$all_vals[$i] = $current_len; | |
//echo "Val: $i Chain Length: $current_len\n"; | |
if($current_len > $max_val['chain_len']) { | |
$max_val['val'] = $i; | |
$max_val['chain_len'] = $current_len; | |
} | |
} | |
print_r($max_val); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment