2015-06-19 20 views
-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 
+1

以調試器和調試您的代碼。 – zerkms

+0

你只是忘了從'smallestCommons'返回''。 'reduce'正在工作。 – Bergi

+0

@Bergi,謝謝,我首先想到'return lcm(a,b);'會給我返回結果。 –

回答

1

您的smallestCommons函數缺少returnundefined是沒有明確的return的所有函數的默認返回值。

function smallestCommons(arr) { 
    return arr.reduce(lcm); 
} 
+0

謝謝,我首先想到返回lcm(a,b);將返回結果。 –

相關問題