[Solved]Smallest Common challenge help needed!

function smallestCommons(arr) {
  var maxArr=Math.max(...arr);
  var mcm=1;
  arr.sort(function(a, b) {
  return a - b;
});
  var denseArr= [];
  for(var i=arr[0]; i<=arr[arr.length-1]; i++){
        denseArr.push(i);
    }
  var mul= denseArr.reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator * currentValue;
  });  
  for (var j=maxArr; j<=mul; j+maxArr){
      mcm= Math.max(...denseArr.map(function(x){return j%x;}));
      if (mcm==0) //I found it!
        {console.log(mcm);}
    }
  return mcm;
}


smallestCommons([1,5]);

Could anyone help me to understand why my second loop is an infinite one?
maxArr= the maximun value in arr;
mul= the product of all the terms of denseArr that contains all the numbers between the smallest and the biggest in arr.

So, I know I will reach mul value if I sum maxArr each time, I don’t change them… so why do the for loop is infinite?

Thank you

I guess this should be: j+=maxArr

Thank you! :slight_smile:
That was one problem.
But it still doens’t work for one test: smallestCommons([23, 18]);

In this case, the infinite loop shows again and I really can’t understand why…

It’s just slow enough that the infinite loop protection kicks off. In the [23,18] case your mul is 72,681,840 and maxArr is 23, so your loop will do Math.max(...denseArr.map(function(x){return j%x;})); 3,160,080 times.

1 Like

uhmm… it might be! :sweat_smile:
I’ll check for faster solutions, thank you! :slight_smile: