用 JavaScript 计算一个范围的最小公倍数


我们需要编写一个函数,它接收一个包含两个数 a 和 b (a >= b)的数组,并返回 [a, b] 范围内所有数的最小公倍数。

方法

我们首先会编写一个基本函数,用于计算两个数的最小公倍数,一旦我们有了这个函数,我们就会在 [a, b] 范围内进行递归调用,最后返回结果。

示例

const lcm = (a, b) => {
   let min = Math.min(a, b);
   while(min >= 2){
      if(a % min === 0 && b % min === 0){
         return (a*b)/min;
      };
      min--;
   };
   return (a*b);
};
const leastCommonMultipleInRange = (arr, len = arr[0], res = 1) => {
   if(len <= arr[1]){
      return leastCommonMultipleInRange(arr, len+1, lcm(res, len));
   };
   return res;
};
console.log(leastCommonMultipleInRange([6, 8]));
console.log(leastCommonMultipleInRange([6, 18]));
console.log(leastCommonMultipleInRange([1, 8]));
console.log(leastCommonMultipleInRange([10, 25]));

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

输出

控制台中的输出为 -

168
12252240
840
26771144400

更新日期:2020-08-25

76 次浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告