Your recursive algorithm is going to have to check a whole lot of coefficients, and so it is no surprise you bump into a stack overflow error.
For finding the least common multiple of a list of numbers, you can use the rule that you can replace any pair in that list with their least common multiple and continue from there. This way you reduce the list step by step until you have one value left.
And actually, it is not needed to really create that list. You can just iterate the values from minimum to maximum and accumulate the least common multiple according to the above principle:
// Euclid's algorithm
function gcd(a, b) {
if (b == 0) return a;
return gcd(b, a % b);
}
function lcm(a, b) {
return a * b / gcd(a, b);
}
// lcm of all numbers in the range [a, b]:
function lcmOfRange(a, b) {
let result = a;
for (let i = a + 1; i <= b; i++) {
result = lcm(result, i);
}
return result;
}
// lcm of all numbers in the range [min(arr), max(arr)]
function lcmOfMinMax(arr) {
return lcmOfRange(Math.min(...arr), Math.max(...arr));
}
console.log(lcmOfMinMax([1, 3])); // 6
console.log(lcmOfMinMax([1, 13])); // 360360
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…