[英]Use reduce() method to find a skipped number in an array of consecutive numbers
[英]Javascript: Use reduce() method to find the LCM in an array
我试图在数组中的几个数字中找到 LCM(最小公倍数)。 为了获得数组中每两个数字之间的 LCM,我使用了无效的reduce()
方法。请告诉我出了什么问题? 谢谢。
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
您的smallestCommons
函数缺少return
。 undefined
是所有没有显式return
函数的默认返回值。
function smallestCommons(arr) {
return arr.reduce(lcm);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.