Smallest Common Multiple, I can't pass with my algorithm

Tell us what’s happening:
I use to make my code in repl.it and there the result is correct however I can’t pass the code in FreeCodeCamp.

Your code so far


function smallestCommons(arr) {
  arr.sort((a, b) => a - b);
  let myArray = [];
  for (let i=arr[0]; i <= arr[1]; i++) {
    myArray.push(i);
  }
  for (let x=1; x < 10000000; x++) {
    let checker = myArray.every(elem => x % elem == 0);
    if (checker) {
      return x;
    }
  }
}


smallestCommons([23,18]);

Your browser information:

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

Link to the challenge:

I use repl.it a lot too. Here’s a link to my own answer to that algorithm if it will help. I remember this one being tricky. :wink:

I would resist peeking at a working solution. Some people spend days working this one out but that is not necessarily a bad thing. Algorithmic thinking improves with practice.

You currently are potentially testing every number up to 10000000 as a possible smallest common. That much looping sets off the infinite loop protection in the FCC environment so your function is shut down prematurely. You will need to eliminate some of the candidates for smallest common that are not mathematical possibilities so you are only testing those that have a reasonable chance of being SCM.

2 Likes

aljazen1 is right.

Just as a hint, do you need to index through every number? For example, if you are trying to find the SCM of 6 and 7, what would be a good place to start indexing? What would be a good number to index by. What if your set was 5, 6, 7? If you know that no two adjacent numbers above 2 are coprime, then you can speed it up even more. Do you have to start on 1? Is there a better place to start? There are other tricks, but that gets you started.