Smallest Common Multiple but last two don't work

Tell us what’s happening:
everything else works, but
smallestCommons[1, 13] and [23, 18] don’t work…
is my code an infinite loop???

Your code so far


function smallestCommons(arr) {
  // creates a variable to store the smallest num
  var start = Math.min(...arr);
  // store the biggest num
  var end = Math.max(...arr);
  var sortedArray = [];
  var LCM = 0, flag = true;
  // adds from smallest to largest values into sortedArray
  for (let i = start; i <= end; i++){
    sortedArray.push(i);
  }

  while (flag){
    LCM++;
    // for all elements in sortedArray,
    for(let n = 0; n < sortedArray.length; n++){
      // if LCM / element gives a remainder which means that number is not divisible by LCM
      if (LCM % sortedArray[n] !== 0){
        // break out of the for loop
        break;
        // if above condition is met (if LCM / element results no remainder), checks if the current element is the last element,
      }else if (sortedArray[n] === end){
        // if current element is the last element in an array, exit the while loop
        flag = false;
      }
    }
  }
  return LCM;
}


smallestCommons([1,5]);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple

Try to run the same code on Codepen or locally and it will work.

The FCC site limits you to a certain (large) amounts of calls or stack size or time-running or whatever. To make your algorithm work you need to make it more efficient.

What I did: try to find the pattern of the numbers that you don’t need to check and then simply skip them. You can make the algorithm a lot more efficient like that.

Good luck!

1 Like

Wow, thank you for giving me a hint!!!
When you said ‘pattern’, I was like… hmmm…
I stared at my whiteboard and just wrote bunch of numbers and figured out the LCM would be one of the numbers within the range of the biggest number in array.
LCM += end; //(sortedArray’sbiggest number)
thank you!

Congratulations!

Spotting patterns and coming up with clever ways to use them is an important skill that will help you in a lot of ways, and it’s worth taking some time to feel good about having done that

If you’re curious, after you’ve passed the challenge, there are some other non-obvious patterns that can be used also

1 Like

I did not know there were other patterns… wow
Thanks for the advice, I will def look into it again!
thank you