Least Common Multiple //JavaScript Repository
Description
Least common multiple of an array of integer numbers.
Created: 2005.11.03 - Modified 2005.11.28
Created: 2005.11.03 - Modified 2005.11.28
Code (Download)
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/mmc [rev. #1]
mmc = function(o){
for(var i, j, n, d, r = 1; (n = o.pop()) != undefined;)
while(n > 1){
if(n % 2){
for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2);
d = i <= j ? i : n;
}
else
d = 2;
for(n /= d, r *= d, i = o.length; i; !(o[--i] % d) && (o[i] /= d) == 1 && o.splice(i, 1));
}
return r;
};
Example (Example)
<form action="">
<fieldset>
<legend>M?nimo M?ltiplo Comum</legend>
<label for="numbers">N?meros:</label> <input type="text" id="numbers" value="2 3 4 7 8" />
<br /><input type="submit" value="Calcular MMC" />
</fieldset>
</form>
<script type="text/javascript">
//<![CDATA[
//http://www.jsfromhell.com/geral/event-listener
addEvent(document.forms[0], "submit", function(e){
alert(mmc(document.forms[0].numbers.value.split(" ")))
e.preventDefault();
});
//]]>
</script>
Help
- mmc(numbers: Array): Integer
-
Returns the least numer able to be divided by all the numbers passed as parameter, the least common multiple.
- numbers
- array of integer numbers
Rank (Votes: 49)
3.20