[SOLVED] Smallest Common Multiple - My code works in the broswer, but times out on the challenge page

It’s apparent that my code isn’t efficient enough to run the challenge, even though my code produces the correct answers through the browser or codepen.

It works fine for smallestCommons([1,5]);, but not smallestCommons([1,13); and smallestCommons([23,18]);.

Please give me suggestions on how to better refactor my code!

  // find bigger and smaller numbers from argument
  var bottom, top;
  if (arr[0] < arr[1]) {
    bottom = arr[0];
    top = arr[1];
  }
  else {
    bottom = arr[1];
    top = arr[0];
  }
  // populate array with range
  var range = [];
  for (var i = bottom; i < top + 1; i++) {
    range.push(i);
  }
  
  
  var searchingForSCM = true; // SCM = smallest common multiple
  var checkForSCM = top;
  var arrayOfDivisibles = [];
  
  /*if check for SMC is divisible by all numbers in range, return it
  if it is.  If not, add the number by itself and check again
  */
  while (searchingForSCM) {
    for (var j = 0; j < range.length + 1; j++) {
      if (checkForSCM%range[j] === 0) {
        arrayOfDivisibles.push(range[j]);
      } // close if
    } // close for
    if (arrayOfDivisibles.length === range.length) {
      arr = checkForSCM;
      searchingForSCM = false;
    } // close if
    else {
      checkForSCM += top;
      arrayOfDivisibles = [];
    } // close else
  } // close while
  return arr;
} // close function

smallestCommons([1,5]);

Bump! Any suggestions welcome, even suggestions on how to approach the problem differently.

Your code is efficient enough. FCC linter/checker doesn’t like “potential infinite loop”.
Add // noprotect as the first line of your code and you’ll be ok.

1 Like

Thank you :D! I edited my code with your suggestion and I passed the challenge.