I am using this JavaScript function to determine the GCD of two values obtained from input fields:
Math.GCD = function(first,second) {
if (first < 0) first = -first;
if (second < 0) second = -second;
if (second > first) {var temp = first; first = second; second = temp;}
while (true) {
first %= second;
if (first == 0) return second;
second %= first;
if (second == 0) return first;
}
};
I would like to extend this to compute the GCD of three numbers, if the user enters a number into a third input field (otherwise, the user will input two and calculate as per this function). Being relatively new to JavaScript, I am not sure how to extend this function for three values. Can anyone help?
Fiddle: https://jsfiddle.net/tjj7won4/1/
Also, I would like to determine the LCM in a likewise fashion, as observed in the fiddle, but, again, I am unsure how to extend the given function. Please, help.
To extend the function for any number of parameters n
, just loop n-1
times over an array of parameters.
This is because mathematically gcd(a,b,c) = gcd(a,gcd(b,c))
Usage: var GCDresult = Math.GCD([16,222,70]); // result: 2
.
// numbers is an array of numbers: ex. [15,20,35,170]
Math.GCD = function(numbers) {
for (var i = 1 ; i < numbers.length ; i++){
// take the next number for GCD with the first,
// and store the result back in the first.
numbers[0] = twogcd(numbers[0], numbers[i]);
}
return numbers[0];
// following is your original GCD function
function twogcd(first, second) {
if (first < 0) first = -first;
if (second < 0) second = -second;
if (second > first) {var temp = first; first = second; second = temp;}
while (true) {
first %= second;
if (first == 0) return second;
second %= first;
if (second == 0) return first;
}
}
};
Your JSFiddle, updated for GCD case is here.