Nate Weiner

This is an old archived post from my former blog The Idea Shower. It's where I cataloged my product explorations and releases, one of which ultimately became Pocket.

This post was published back in 2008. It may not function as originally intended or may be missing images.

Least Common Mulitple and Greatest Common Factor (LCM,GCF) in PHP and Javascript

January 22, 2008

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.

Usage

To calculate the Greatest Common Factor of two numbers, use the 'gcf' function. Ex: gcf(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 gcf($a, $b) { 
	return ( $b == 0 ) ? ($a):( gcf($b, $a % $b) ); 
}
function lcm($a, $b) { 
	return ( $a / gcf($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 gcf(a, b) { 
	return ( b == 0 ) ? (a):( gcf(b, a % b) ); 
}
function lcm(a, b) { 
	return ( a / gcf(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];
	}
}