Smallest Common Multiple with for loops

The page tells me 5/6 are corect but idk how to solve the one that’s remaining (whichis smallestCommons([2, 10]) should return 2520.)
The code although long seems ok to me, can’t find the solution.

function smallestCommons(arr) {
  let fullarr = arr.sort().slice();
  let position = 1;
  let count = 0;
  let LCM = 2;
  
  for (let x = arr[0] + 1; x < arr[1]; x++) //full the array with nubmer between input: arr[0] and arr[1]
  {
      fullarr.splice(position, 0, x);
      position++;
  }
  

  for (LCM; count < fullarr.length; LCM++) //select number thats gonna be loooped through array,
  {
    for (let j = 0; j < fullarr.length; j++) //loop through each number of the array to check for LCM
    {
        if (LCM % fullarr[j] === 0) 
        {
          count++; //if remainder is 0 we add 1 to count. Once it gets to count === arr.length we found LCM
        }
        else 
        {
            count = 0;
        }
    }
  }
  console.log(LCM)
  return LCM - 1;
}

smallestCommons([2,10]);

In this line here:

  let fullarr = arr.sort().slice();

This is where your problem is.

Your first instinct when things are working the way you expect should be to log things out and see where the issue is. If you had logged out fullarr, you would have seen the issue.

The sort method has an issue when dealing with numbers.

1 Like

This is a wrong way to use a for loop. Don’t do this. Really. Don’t.


This is a correct but inefficient overall approach, which means that it will take too long on some browsers and the tests will abort due to infinite loop protection.

You can either make this slightly less inefficient so that it takes less time and doesn’t trigger loop protection or you can replace this approach with the GCD based algorithm found on Wikipedia.

The way you have disguised a while loop as a for loop makes it harder to clearly point at how to make this less inefficient, so if you want to go that route, I would first rewrite that outer for loop as an actual while loop. You really shouldn’t (ab)use the for loop syntax like that anyway.

2 Likes

Thanks, I didn’t even notice that. Yeah, don’t use a for loop that way.

2 Likes

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