Intermediate Algorithm Scripting - Smallest Common Multiple

Tell us what’s happening:
I’ve solved this problem but I’m also aware that this is very inefficient. It technically passes the test but doesn’t because it’s an infinite loop. I’ve checked the values that it gives on VSC and I’m pretty sure the logic is right at least. Any tips :sweat_smile:

Your code so far

function smallestCommons(arr) {
  let lcm = 1;
  arr.sort(
    (a,b) => {
      if (a > b){
        return 1;
      } else {
        return -1;
      }
    }
  );
  let a = arr[0];
  let b = arr[1];
  let rangeArr = [];
  for (let z = 0; z < (b-a)+1;z++){
    rangeArr.push(a+z)
  }
  console.log(rangeArr);

  for (let i = 1; i < 100000; i++){
    let divisibleCounter = 0;
    for (let j = 0; j < rangeArr.length;j++){
      if (b*i % rangeArr[j] == 0){
        divisibleCounter += 1;
      }
      if (divisibleCounter == rangeArr.length){
        console.log(b*i)
        return (b*i);
      }
    }
  }
}

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/107.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

Link to the challenge:

You don’t need this array.

You can pick better start, stop, and increment values here.

You can improve the performance of your core algorithm. You could also try the gcd/lcm based algorithm.

1 Like

My suggestion is to google some math algorithms and try to implement them. (Don’t google the code just the mathematics behind the idea)

1 Like

i think the infinite loop warning is just how the test suite / code editor is set up, but check out ‘get hint’ to see a more efficient similar method without the hard coding a very high number of iterations.
at least that my take.