Intermediate Algorithm Scripting - Smallest Common Multiple

Tell us what’s happening:
My solution works, but looks so very different to the solutions in the hint tab. Is this a problem? Any ideas as to how my thinking may be “wrong” would be most appreciated :slight_smile:

  **Your code so far**
function smallestCommons(arr) {
if (arr[1] < arr[0]) {
  arr = [arr[1], arr[0]];
}
let between = []
for (let i = arr[0]; i < arr[1] + 1; i++) {
  between.push(i);
}
for (let i = arr[1]*arr[0]; i > 0 ; i += arr[1]) {
  if (between.every(a => (i % a === 0))) {
   return i
 }
}
}

console.log(smallestCommons([23, 18]));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

Link to the challenge:

Explicitly coding an infinite loop is a bad idea.

Here an attempt with bounded i. My initial thinking was that, as there must be some i for which between.every(a => (i % a === 0)) = true, the loop will be exited.

  if (arr[1] < arr[0]) {
    arr = [arr[1], arr[0]];
  }
  let between = []
  for (let i = arr[0]; i < arr[1] + 1; i++) {
    between.push(i);
  }
  for (let i = arr[1]*arr[0]; 
  i < between.reduce((a, b) => a*b);
  i += arr[1]) {
    if (between.every(a => (i % a === 0))) {
      return i
    }
  }
}

It is true that if your code is correct, then you won’t have an actual infinite loop, but by explicitly coding an infinite loop you could actually get an infinite loop from a bug or change in your code. It’s best to avoid the possibility.

Since this array isn’t being replaced, you should use const here.

I’m personally not wild about allocating an array that is a contiguous range of numbers. It’s a workaround some people use for the fact that JS doesn’t yet have a proper range iterator, but it is somewhat inefficient compared to a traditional loop.

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