计算某个范围内的最小公倍数 JavaScript
javascriptweb developmentobject oriented programming更新于 2025/10/8 19:56:17
我们需要编写一个函数,该函数接受两个数字 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]));
输出
控制台中的输出将是 −
168 12252240 840 26771144400
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

