簡體   English   中英

Javascript:使用 reduce() 方法在數組中查找 LCM

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM