Smallest Common Multiple - Last Test Not Passing

Hi Guys,
every test in the challenge passes, but not the last one
"smallestCommons([23, 18]) should return 6056820."

When I run my code in Atom or Chrome, I get the correct answer. I thought maybe on the FCC site there’s some infinite loop prevention mechanic, but I don’t have a clue how to write it more efficient. Does anyone have an idea? Thanks!

My code:

function smallestCommons(arr) {

  // sort in case arr is not ordered
  let sorted = arr.sort((a, b) => a - b);

  // create range
  let range = [];
  for (let i = sorted[0]; i <= sorted[1]; i++) {
    range.push(i);
  }
  console.log(range);

  let counter = range[0];
  while (true) {

    // convert arr depending if counter is divisible by el in range
    let isDivisibleArr = range.map(x => counter % x == 0);

    // if counter is divisible by **every** el in range, return counter
    if (isDivisibleArr.every(el => el == true)) {
      return counter;
    } else {
      // if not, increase counter by one and try again
      counter++;
    }
  }
}
console.log(smallestCommons([23, 18]));

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

I know you’ve withdrawn your comment, but you really got me thinking @InternetFriend !
I changed counter++; to counter += range[0]; and it works! (And is muuuch faster!) Thank you!

What I did was like bruteforcing every single number until one matches, but it turns out I only have to try with multiples from the smaller given number.

It may be that your code is triggering the infinite loop protection because it is taking too much time to run

Haha, I withdrew my comment because it’s 5 AM, I haven’t had my coffee, and I couldn’t figure out if I said the right thing. Glad I’m not totally useless at this hour.

1 Like