Can't find apparent infinite loop in Smallest Common Multiple function?

Can't find apparent infinite loop in Smallest Common Multiple function?
0

#1

Hi all - I am getting the right answers for this function when I run in node in my terminal, but the FCC console keeps telling me I have an infinite loop on the line where my for loop begins.

"Error: potential infinite loop at line 11.To disable loop protection, write:
// noprotect as the first line. Beware that if you do have an infinite loop in your code this will crash your browser. " I think I probably don’t want to use //nonprotect.

It seems to work with all but the last example, smallestCommons([23, 18]). All the others appear checked. And as I said, when I try this in my terminal it works fine and spits out the correct number, 6056820.

Any advice? I feel like I’m missing something small and easy but I just can’t see it! Any help is greatly appreciated. My code is below.

function smallestCommons(arr) {
  
  arr.sort(function(a, b){return a-b;});
  console.log(arr);
  var j = 0;
  var i = 1;
  var trying = true;
  
  while (trying) {
    for (j=arr[0]; j<arr[1]+1; j++) {
      if (i%j !== 0){
        break;
      }
      
      else if (j==arr[1]) {
        trying = false;
        console.log(i);
        return i;
      }
      else {
        continue;
      }
      
    }
    
    i++;
  }
}

smallestCommons([23, 18]);

#2

First off use triple backticks to post code in the forum. See this post for more details.

Secondly, its most likely not an infinite loop, but rather a loop that runs an excessive number of times. I ran into the same issue when I was doing that challenge. There is a more efficient algorithm that will allow you to pass the challenge. If you want I can post my solution, or you can try puzzle it out?


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See @JavaTheNutt’s link for details.


#4

It is “potential” infinite loop because you have trying in your while loop which gets changed in the else if statement and “potentially” could never be reached.

Regarding your code - do you really need to increment i by one?