[英]GCD of more than 2 numbers
function gcd (a, b) {
if(b == 0){
return a;
}
return gcd(b, a%b);
}
function gcd_more_than_two_numbers (a) {
var last = Math.max.apply(null, a);
var first = Math.min.apply(null, a);
return gcd(first, last);
}
console.log(gcd_more_than_two_numbers([9999,213123,9,15,27]));
console.log(gcd_more_than_two_numbers([5,10,15,25]));
Is it right to take the lowest and the highest values in an array and find a gcd for all the numbers between them ? 取数组中的最低和最高值并为它们之间的所有数字找到一个gcd是否正确? Is it mathematically right ?
数学上正确吗?
Is it right to take the lowest and the highest values in an array and find a gcd for all the numbers between them ?
取数组中的最低和最高值并为它们之间的所有数字找到一个gcd是否正确? Is it mathematically right ?
数学上正确吗?
NO . 不行
You need to take the gcd of the first pair and then recalculate against all the other elements of the array, you can do that easily with reduce
: 您需要获取第一对的gcd,然后针对数组的所有其他元素重新计算,您可以使用
reduce
轻松实现:
function gcd (a, b) { if(b == 0){ return a; } return gcd(b, a%b); } function gcd_more_than_two_numbers (a) { return a.reduce(gcd) } console.log(gcd_more_than_two_numbers([9999,213123,9,15,27]))
No it isn't. 不,不是。
The identity you're after is gcd(a, b, c) = gcd(gcd(a, b), c)
. 您所追求的身份是
gcd(a, b, c) = gcd(gcd(a, b), c)
。
I suggest you unpick the recursion using a loop. 我建议您使用循环取消选择递归。
function gcd() { var arr = Array.prototype.slice.call(arguments); return arr.reduce(function(a, b) { if (b == 0) { return a; } return gcd(b, a % b); }); } console.log(gcd(7,14)); console.log(gcd(9999,213123,9,15,27)); console.log(gcd(5,10,15,25));
You can use array.every
as well to check validity: 您也可以使用
array.every
检查有效性:
function getGCD(arr) { var min = Math.min.apply(null, arr); var gcd = 1; for (var i = gcd + 1; i <= min; i++) { if (arr.every(x => x % i === 0)) gcd = i; } return gcd; } var arr = [100, 13000, 1110]; var arr2 = [9999, 213123, 9, 15, 27] console.log(getGCD(arr)) console.log(getGCD(arr2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.