I would imagine this is a good time to tell my Math teacher that maybe he was right and I would need this in the real world.
While working on Idea 27, I needed a script to calculate the least common multiple from a set of numbers. To my surprise I had some difficulty finding a script to do that. So I brushed up on my 6th grade math and made one.
I’ve added a set for both PHP and Javascript below, I’m sure you could easily read them for any language.
Useage
To calculate the Greatest Common Multiple of two numbers, use the ‘gcm’ function.
Ex: gcm(6, 10)
To calculate the Least Common Multiple of two numbers, use the ‘lcm’ function.
Ex. lcm(6, 10)
To calculate the Least Common Multiple of more than two numbers, enter an array into the lcm_nums function.
Ex: lcm_nums( array(6, 10, 4, 9, 54) )
PHP Code
function gcm($a, $b) {
return ( $b == 0 ) ? ($a):( gcm($b, $a % $b) );
}
function lcm($a, $b) {
return ( $a / gcm($a,$b) ) * $b;
}
function lcm_nums($ar) {
if (count($ar) > 1) {
$ar[] = lcm( array_shift($ar) , array_shift($ar) );
return lcm_nums( $ar );
} else {
return $ar[0];
}
}
Javascript Code
function gcm(a, b) {
return ( b == 0 ) ? (a):( gcm(b, a % b) );
}
function lcm(a, b) {
return ( a / gcm(a,b) ) * b;
}
function lcm_nums(ar) {
if (ar.length > 1) {
ar.push( lcm( ar.shift() , ar.shift() ) );
return lcm_nums( ar );
} else {
return ar[0];
}
}
Comments (4)
Leave a Reply