I have been working on a code snippet to find the Greatest Common Denominator (GCD) of two or three numbers. Here is what I have so far:
Math.GCD = function(numbers) {
for (var i = 1 ; i < numbers.length ; i++){
if (numbers[i] || numbers[i] === 0)
numbers[0] = twogcd(numbers[0], numbers[i]);
}
return numbers[0];
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;
}
}
};
Math.LCM = function(first,second) {
return first * (second / this.GCD(first, second)); // STRUGGLING TO EXTEND THIS TO THREE #s
};
// example
console.log(Math.GCD([4, 5, 10]));
Take note of the part in the code related to the Least Common Multiple (LCM)
I am currently attempting to expand this functionality to calculate the LCM of either two or three user-inputted values. Unfortunately, I'm having trouble getting it right. As an amateur in JavaScript, any assistance would be greatly appreciated. Remember that if a value is left empty, it should not be included in the computation similarly to how it's done with the GCD.