Question about my Recursive Solution

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

Link to the challenge:

Have you tried adding any console log statements to see what’s happening?

Does it work I don’t think so because i found an logical error in the code like infinite loop error…

I tried logging all through it, but didn’t get anything that untangled it

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!

Adding these logs

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.