Smallest Common Multiple Challenge-

Intermediate Algorithm Scripting: Smallest Common Multiple

Greetings,

I’ve been trying to solve this challenge independently for a few hours now, and I’ve pretty-much found my solution. However, for some reason the code stops functioning when one of the given arguments is 23 or higher (as in the last criteria for the challenge). When given these arguments, it returns undefined. My guess is that it could be to do with the code looping too many times, as it’s a rather clunky solution. But I don’t know for sure, so any clarity would be much appreciated.

Thank you :slight_smile:

My code so far



function smallestCommons(arr) {
  
         // sort array and calculate range of numbers
 
  arr.sort((a, b) => a - b);
 let rangeArr = [];
  for (let i = arr[0]; i <= arr[1]; i++) {
    rangeArr.push(i);
  } 
 
            // calculate Least Common Multiple
  
  let LCM = arr[1];
  
  while (LCM % arr[0] !== 0) {
       LCM += arr[1];
  } 
  
  
  
  let counter = 0;
  while (counter !== rangeArr.length){
  for (let j = 0; j < rangeArr.length; j++) {
    if (LCM % rangeArr[j] === 0) {
      counter++;
    } 
      }
    
 if (counter == rangeArr.length) {
   return LCM;
 }
  else {
    LCM += arr[1];
    counter = 0;
  }
  }
}


console.log(smallestCommons([1,13]));

Your browser information:

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

This challenge is usually the first one people trip up on where their solutions take too long to run and get killed by the infinite loop protection

I wish it was more obvious when that happens, but apparently someone is working on that(?)

Something you might find will speed this up a lot, is that one can find the LCM of a pair of numbers from the GCD (greatest common denominator) of the pair, and the GCD has a fairly elegant famous algorithm for it

the LCM and GCD of a set of numbers is an accumulation: (e.g for 3 numbers: GCD(a,b,c) = GCD(GCD(a, b), c))

If the above is unclear in some way let me know, though there are other ways to solve it of course

1 Like

Thank you very much. I was able to solve it with your help

2 Likes