Skip to content

Instantly share code, notes, and snippets.

@remoharsono
Created September 17, 2015 08:19
Show Gist options
  • Save remoharsono/867584825712870ed10f to your computer and use it in GitHub Desktop.
Save remoharsono/867584825712870ed10f to your computer and use it in GitHub Desktop.
<?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