[英]Javascript: Use reduce() method to find the LCM in an array
I am trying to find the LCM(least common multiples) among several numbers in an array.我试图在数组中的几个数字中找到 LCM(最小公倍数)。 To get a LCM between each two numbers in the array, I use the
reduce()
method which is not working.Please tell me what's wrong?为了获得数组中每两个数字之间的 LCM,我使用了无效的
reduce()
方法。请告诉我出了什么问题? Thanks.谢谢。
function gcd(a,b){
//gcd: greatest common divisor
//use euclidean algorithm
var temp = 0;
while(a !== 0){
temp = a;
a = b % a;
b = temp;
}
return b;
}
function lcm(a,b){
//least common multiple between two numbers
return (a * b / gcd(a,b));
}
function smallestCommons(arr) {
//this function is not working, why?
arr.reduce(function(a, b){
return lcm(a, b);
});
}
smallestCommons([1,2,3,4,5]);
//------>undefined
Your smallestCommons
function is missing a return
.您的
smallestCommons
函数缺少return
。 undefined
is the default return value for all functions that don't have an explicit return
. undefined
是所有没有显式return
函数的默认返回值。
function smallestCommons(arr) {
return arr.reduce(lcm);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.