Am I just not being efficient enough?

Tell us what’s happening:
Describe your issue in detail here.
I am trying to get this challenge done and it seems that the returned values are correct. The issue is that the larger numbers are never being executed because it reaches the maximum call size. Am I just being that inefficiant? Or is it some other issue?

   **Your code so far**

function smallestCommons(arr) {
 // this orders the arr

 let numArray = arr
 numArray = numArray.sort(function (a, b) {  return a - b;  });

 // this lists the values to check

 let checkList = []
 for (let i = numArray[0]; i < numArray[1]; i++){
   checkList.push(i)
 }

 // this is the checkFunction

 function algo(value1, value2, counter, list){
   if (list.filter(a => (value2 * counter) % a != 0).length == 0){
     return(value2*counter)
   }
   else{
     return algo(value1, value2, counter+1, list)
   }

 }
return algo(arr[0],arr[1], 1, checkList)


}
smallestCommons([1,13]);
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36

Challenge: Smallest Common Multiple

Link to the challenge:

1 Like

This is a bad use case for recursion. In general, you rarely want to use recursion.

But even if you converted this into an actual loop, the approach you have chosen is still pretty slow. I would instead look up on Wikipedia how to compute the LCM and GCD. Interestingly, the algorithm on Wikipedia is actually showing a good use case of recursion.

1 Like

Thanks for the pointers. Still figuring out when to use recursion.

1 Like

That’s pretty common. The general rule of thumb is that if you have any doubts about if recursion fits, then it definitely does not. I’ve used it once in professional code, and that was to manually implement object inheritance.

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