Greatest Common Divisor //JavaScript Repository
Description
Greatest common divisor of an array of integer numbers.
Created: 2005.11.03
Created: 2005.11.03
Code (Download)
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/mdc [rev. #1]
mdc = function(o){
if(!o.length)
return 0;
for(var r, a, i = o.length - 1, b = o[i]; i;)
for(a = o[--i]; r = a % b; a = b, b = r);
return b;
};
Example (Example)
<form action="">
<fieldset>
<legend>Greatest Common Divisor</legend>
<label for="numbers">Numbers separated by espace:</label> <input type="text" id="numbers" value="32 48 8" />
<br /><input type="submit" value="Calculate GCD" />
</fieldset>
</form>
<script type="text/javascript">
//<![CDATA[
//http://www.jsfromhell.com/geral/event-listener
addEvent(document.forms[0], "submit", function(e){
alert(mdc(document.forms[0].numbers.value.split(" ")))
e.preventDefault();
});
//]]>
</script>
Help
- mdc(numbers: Array): Integer
-
Returns the greatest number able to divide all the numbers in the first argument, the greatest common divisor.
- numbers
- array of integer numbers
Rank (Votes: 37)
3.14