-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);'會給我返回結果。 –