Algorithm Scripting: Smallest Common Multiple - Help?

Hi everyone, this is my first time posting on this forum, so please excuse me if I haven’t posted this in the right place or if I am formatting this wrong. My dilemma is that I am having trouble with the following problem:

Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
The range will be an array of two numbers that will not necessarily be in numerical order.
For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6.

I came up with the following as a solution, and it works for every array except for (23,18):

function smallestCommons(arr) {
  arr.sort((a,b) => a - b);
  let numArr = [ ];
  let counter = arr[1];
  for(let i = arr[0]; i <= arr[1]; i++) {numArr.push(i);}
  while(numArr.every(num => Number.isInteger(counter / num)) === false) {
  counter += arr[1];
  return counter;

Now, I think this eventually would work, but the reason why freeCodeCamp says that this particular test could be failing is because it thinks this solution is a potential loop because it has to work through 6056820 iterations, which is a lot and not the most effective solution I realize. All of my other tests prior to this one past, it’s just this last one that I need. I would love to hear anyone’s feedback if you have any suggestions on how I could potentially rework my code so that it doesn’t think I’m creating an infinite loop. Thanks :slightly_smiling_face:

Hello and welcome to the freeCodeCamp community~!

I would recommend looking at the Euclidian greatest common divisor approach:

I found this to be performant enough to pass the tests. :slight_smile:

Thank you for the suggestion, I did try that out and it worked! :smiley:

1 Like