DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Minimum Common Multiple //Javascript Function

07.30.2005
| 6423 views |
  • submit to reddit
        <a href="http://jsfromhell.com/math/mmc">
Minimum Common Multiple

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>


Code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math.mmc [v1.0]

MCM = function( divisors ){
	for( var i, j, n, d, r = 1, x = divisors; ( n = x.pop() ) != undefined; )
		while( n > 1 ){
			if( !( n % 2 ) )
				d = 2;
			else {
				for ( i = 3, j = Math.floor( Math.sqrt( n ) ); i <= j && n % i; i += 2 );
				d = i <= j ? i : n;
			}
			for( i in ( n /= d, r *= d, x ) )
				x.splice( i, !( x[i] % d ) && ( x[i] /= d ) == 1 );
		}
	return r;
}


Usage

alert( MCM( [2, 2, 4, 6, 9] ) );