Greatest Common Demonimator
Utility Function
by peterbenoit
HTML
<input type="text" value="[240,600,360,1200]" />
<input type="button" value="GCD" />
JavaScript
// gcd utility function
// usage:
// gcd([240, 600, 360, 1200]);
// or with strings
// gcd([240, '600', 360, 1200]);
function gcd(arr) {
if (!Array.isArray(arr)) {
return undefined;
}
return arr.reduce(function(a, b, i, arr) {
if (+a < 0) {
a = -(+a);
}
if (+b < 0) {
b = -(+b);
}
if (+b > +a) {
var temp = +a;
a = +b;
b = temp;
}
while (true) {
a %= b;
if (a === 0) {
return b;
}
b %= a;
if (b === 0) {
return a;
}
}
}, arr[0]);
}
$(":button").click(function() {
console.log(gcd(eval($(":text").val())));
});