Smallest Common Multiple optimization feedback

Smallest Common Multiple optimization feedback
0.0 0

#1

Ok, so I’ve optimized this quite a lot from my initial attempts. Initially, though it got the right answer, it took too long in the test so it timed out. Took me 4 iterations before I came up with this, which turned out to be REALLY FAST at getting the answer to the smallest multiple of the list of numbers.

I’d really like feedback on this, how clean is it, and is it really as fast as I think, or am I still being inefficient in my approach?

BTW, yes this iteration passed the test almost instantly when I clicked “Run Test” so I’m not asking for any help solving it. This particular challenge was less a challenge on how to solve the problem, but more a challenge on how to solve it efficiently, and so that is why I would like feedback, so I can further improve the efficiency of my future code.

Your code so far

function smallestCommons(arr) {
  var a = 0;
  var b = 0;
  if(arr[0] > arr[1]) { a = arr[0]; b = arr[1]; }
  else { a = arr[1]; b = arr[0]; }
  
  var numlist = makelist(a, b);
  
  var multiple = 0;
  var countby = a * (a-1);
  var found = false;
  while(!found) {
	found = true;
	multiple += countby;
	for(var n in numlist){
		if(multiple % numlist[n] != 0) { found = false; }
	}
  }
  
  return multiple;
}

function makelist(a, b) {
    var list = [];
    for(var i = b; i <= a; i++) {
      list.push(i);
    }
    return list;
}

smallestCommons([1,5]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:


#2

You can make it up to 100x faster using Greatest Common Divisor + Least Common Multiple, if it’s worth the effort.