I’m tackling the intermediate JS Algorithm problems, and was finishing the Smallest Common Multiple one. I’ve written the following recursive function, which I don’t believe have an infinite loop, yet I still get the error of Maximum call stack size exceeded. Is there a logical error, or is this just not an acceptable way for me to tackle this problem? Thanks!

Your code so far

function getNumber(num, min, max) {
for(let i = min; i<=max; i++){
if(num % i !== 0){
return getNumber(num+max, min,max)
}
}
return num
}
function smallestCommons(arr) {
const sortedArr = arr.sort(function(a, b){return a-b})
const min = sortedArr[0]
const max = sortedArr[sortedArr.length -1]
return getNumber(max, min, max)
}
smallestCommons([23,18])

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

No like I said, this kept giving me infinite loop errors, but I was just wondering if anyone can point to me where my logical error was. I already found an alternative solution to this problem so I’m not stuck, just wonder if anyone can see what I’ve done wrong here because I’m just curious heh. Thanks for the replies!

function getNumber(num, min, max) {
console.log("num:", num, "min:", min, "max:", max);
for (let i = min; i <= max; i++) {
console.log(" remainder:", num % i);
if (num % i !== 0) {
return getNumber(num + max, min, max);
}
}
return num
}
function smallestCommons(arr) {
const sortedArr = arr.sort(function (a, b) { return a - b });
const min = sortedArr[0];
const max = sortedArr[sortedArr.length - 1];
return getNumber(max, min, max);
}
console.log("done:", smallestCommons([1, 13]));

It looks like you just might have too much recursion. You don’t really need the recursion for this approach to work, so I think you’re just inadvertently overwhelming the callstack here.