-
-
Save al-the-x/3811849 to your computer and use it in GitHub Desktop.
PHP solution for http://www.reddit.com/r/dailyprogrammer/comments/zx98u/9152012_challenge_98_intermediate_multiple_cycling/
This file contains 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 | |
function next_highest_multiple($number, $multiple) | |
{ | |
if ( $multiple > $number ) return $multiple; | |
if ( $multiple == 0 ) return 0; | |
return ( ($remainder = $number % $multiple) ? | |
$number + $multiple - $remainder : $number | |
); | |
} | |
function multiple_cycle($limit, array $numbers) | |
{ | |
$current = 0; $cycles = 0; | |
while ( $current < $limit ) | |
{ | |
$cycles++; | |
$current = next_highest_multiple($current, current($numbers)); | |
next($numbers) or reset($numbers); | |
} | |
return $cycles; | |
} | |
assert('multiple_cycle(15, array(5, 7, 3)) == 6') or var_dump( | |
multiple_cycle(15, array(5, 7, 3)) | |
); | |
var_dump(multiple_cycle(1000000000, array(5395, 7168, 2367, 9999, 3))); |
Author
al-the-x
commented
Oct 1, 2012
Still room for optimization, of course. That 3
term in the $numbers
array takes a LONG time to catch up to the others on 15-16.
With the next_highest_multiple()
calculation, I get much more respectable benchmarks and a different answer!
int(408626)
real 0m7.536s
user 0m7.488s
sys 0m0.033s
Which one is right? Damned if I know...! :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment