Home  »  Solutions  »  Least/Greatest Common Mulitple (LCM,GCM) in PHP and Javascri...
Preview of Least/Greatest Common Mulitple (LCM,GCM) in PHP and Javascript

Least/Greatest Common Mulitple (LCM,GCM) in PHP and Javascript

Nate Weiner - Posted in Solutions, , , Comments (3)

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 (3)


  1. I think you must mean “Greatest Common Divisor” rather than “Greatest Common Multiple” as the GCM would be infinity for any set of numbers

    May 24th, 2008 PoloDePoli
  2. Did you make your code unreadable on purpose?

    June 21st, 2008 Matt
  3. @Matt (Sass Train), the formatting must have gotten screwed up over the design update. I’ve fixed it now.

    June 21st, 2008 Nate Weiner

Leave a Reply