2015-06-19 64 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);将返回结果。 –

相关问题