我正在使用这个JavaScript函数来确定从输入字段中获得的两个值的GCD:
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;
}
};
我想将其扩展为计算三个数字的 GCD,如果用户在第三个输入字段中输入一个数字(否则,用户将输入两个并按照此函数进行计算)。作为 JavaScript 的新手,我不确定如何将这个函数扩展到三个值。谁能帮忙?
小提琴:https://jsfiddle.net/tjj7won4/1/
另外,我想以同样的方式确定LCM,正如在小提琴中观察到的那样,但是,同样,我不确定如何扩展给定的功能。请帮忙。
> 要扩展任意数量的参数n
函数,只需在参数数组上循环n-1
次即可。
这是因为数学上gcd(a,b,c) = gcd(a,gcd(b,c))
用法: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;
}
}
};
您的 JSFiddle,针对 GCD 案例进行了更新,请点击此处。
你可以使用相同的函数来接受任意数量的参数。
你也可以扩展它:小提琴
Math.GCDe = function() {
var result = arguments[0];
for (var i=1;i<arguments.length;i++)
result = this.GCD(result,arguments[i]);
return result;
}