Why is my code slow? Smallest Common Multiple challenge

Why is my code slow? Smallest Common Multiple challenge


The code below seems to work correct, but I can barely finish for [1,2] and [1,3]. I havent tried it for big arrays. Could you please comment, what is wrong with this code?

Fir I am creating reverse array of numbers between max and min.

Then I use arrar.reduce to calculate LCMs.

 function smallestCommons(arr) {
      var marr=[];
      var mi=Math.min.apply(null,arr);
      var ma=Math.max.apply(null,arr);
  for (var a=ma; a>=mi; a--){marr.push(a);}
  return marr.reduce(function lcm(a, b) {
   var aa=arguments[0];
   var bb=arguments[1];
     if (aa%b===0){return aa;}
     if (bb%a===0){return bb;}

smallestCommons([1, 2]);


unfortunately your code dosent work … eg numbers 8,5 your marr would be [8,7,6,5]
you then check 8%7 and if not 0 go 8*2 =16 check 16%7 etc till gets to 56 then its 0
while also checking 7
when 56 it then changes to numbers and uses 56 and 6 so you get 12%56 24%56 etc and never finds one that gives 0 and you have 112%6 224%6 etc and never finds one that gives 0 … you are now stuck in a infinite loop

you need to change from the reduce function down and work out first how to get the scm and then code it … i would suggest googling how to get smallest common multiple … understand how its obtained and then you will find it easier to code a sloution.
if you are wondering how i can see what is happening in your code … i created a var count =0 at the beginning of your code … then i changed your while to while(count <100){ … added count ++; after your last bb=bb*2; … and then put console.logs in your if statements to console.log(aa +’ '+ b) and the same for bb a …
doing this i could see what is going on for the first 100 loops and what the values are changing too and where is the problem



Thank you for reviewing the code also for valuable hint how to debug the while loop.