Help with common multiple

function smallestCommons(arr) {

  var max = Math.max(arr[0],arr[1]);
  var min = Math.min(arr[0],arr[1]);
  var arrAll = [];
  var divider = 0;
  for (var i = min; i <= max; i++) {

  	console.log( "numbs " + i);
  	arrAll.push(i);
  }
 


  return isNums(arrAll,0,max);

}

function isNums(arr,i,num){
	if (i === arr.length) {
		return num;
	}
	if (num % arr[i] !== 0) {
		return isNums(arr,0,num+1);
	}
	return isNums(arr,i+1,num);
}

When the array is 1,5 like the example the output is 60 (OK)
But when the output should be bigger like the example 18,23 I get Maximum call stack size exceeded

You’ve made too many recursions.Try to use loops instead.

I don’t know how much loops I need for FOR loops so I’ll try using while loop.
What is the deep reason for that problem? Why can the computer handle 1 million for loops but cannot handle fewer recursion calls?

I would say it’s a great use case for a while loop.

As for the reason for that recursion limit, I don’t know.It’s not a limit set by the computer but by the environment, read this : http://www.2ality.com/2014/04/call-stack-size.html

Thanks, solved it.
(Pretty nasty solution)

SPOILER ALERT

    var isOk = false;
	var common = 0;
  var max = Math.max(arr[0],arr[1]);
  var min = Math.min(arr[0],arr[1]);
  var arrAll = [];
  num = max;
  for (var i = max; i >= min; i--) {
      console.log( "numbs " + i);
      arrAll.push(i);
  }
  // alert(arrAll);

	while(!isOk){
		for (var d = 0; d < arrAll.length; d++) {
			if (num % arrAll[d] !== 0){
				num++;
				break;
			}
			if (d === arrAll.length -1) {
				common = num;
				isOk = true;
			}
		}

			
	}
  return common;
2 Likes