为任意数量的参数扩展函数
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;
}
}
};
为GCD案例更新的JSFiddle是
here
.