Smallest Common Multiple - trying to do 360 360 loops

Tell us what’s happening:
In theory, my solution should work. Basically, I check every conceivable number from 1 to as high as it needs to go against the range of factors. Unfortunately, it’s a brute force method that requires the computer to loop as many times as necessary to get the right number (which could mean up to hundreds of thousands of loops). The computer refuses to do that many loops lol!

I’m not a math major, so there’s no way I can figure out a more elegant solution without looking at the hints. While the basic solution doesn’t require as many loops, it’s still a lot (2310 loops). So at what point does the computer decide it’s had enough and gives up looping?

As for the Euclidean Algorithm… That is way beyond me.

Your code so far


function smallestCommons(arr) {
  let range = [];
  if (arr[0]<arr[1]){
    for (let i = arr[0]; i <= arr[1]; i++){
      range.push(i);
    }
  } else {
    for (let i = arr[1]; i <= arr[0]; i++){
      range.push(i);
    }
  }
  console.log(range);
  for (let j = 1; true ; j++){
    //console.log(j);
    for (let i = 0; i<range.length; i++){
      if (j%range[i] !== 0){
        i = range.length;
      }
      if (i == range.length-1){
        return j;
      }
    } 
  } 
}


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

Your browser information:

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

Link to the challenge:

It’s not the number of loops, it is the time needed computing
So it also depends on device and environment (as same computation may be faster or slower in different environments)
Once the loop has gone for too many milliseconds, it is stopped

1 Like