Nate Weiner

  • Archive
  • RSS

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

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];
	}
}
    • #javascript
    • #math
    • #php
  • 4 years ago
  • 4
  • Permalink
  • Share
    Tweet

About

Prototyper, water waster, developer of Pocket.

 

Follow

Twitter: @NateWeiner
Vimeo: Nate Weiner
500px: Nate Weiner
Blog: RSS

Pages

  • Contact
  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr