-3
我试图在数组中的几个数字中找到LCM(最小公倍数)。为了在数组中的每两个数字之间得到一个LCM,我使用reduce()
方法,该方法不工作。请告诉我什么是错的?谢谢。Javascript:使用reduce()方法查找数组中的LCM
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
以调试器和调试您的代码。 – zerkms
你只是忘了从'smallestCommons'返回''。 'reduce'正在工作。 – Bergi
@Bergi,谢谢,我首先想到'return lcm(a,b);'会给我返回结果。 –