Created
September 17, 2015 08:19
-
-
Save remoharsono/867584825712870ed10f to your computer and use it in GitHub Desktop.
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 | |
// Greatest Common Divisor and Least Common Multiple | |
function lcm_arr($items){ | |
// Input: An Array of numbers | |
// Output: The LCM of the numbers | |
while(2 <= count($items)){ | |
array_push($items, lcm(array_shift($items), array_shift($items))); | |
} | |
return reset($items); | |
} | |
function gcd($n, $m) { | |
$n = abs($n); | |
$m = abs($m); | |
if ($n==0 and $m==0) | |
return 1; //avoid infinite recursion | |
if ($n==$m and $n>=1) | |
return $n; | |
return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n); | |
} | |
function lcm($n, $m) { | |
return $m * ($n/gcd($n,$m)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment