Related to challenge - Smallest common multiple finder

I am getting infinite loop error on line 17 for some reason (It is this line- var divCheck = checkSequentialDivisions(arr, arr[0] * i);). I am unable to find it.

function checkSequentialDivisions(arr, scm){
  console.log(arr, 'arr', scm, 'scm');
  var lowestNum = arr[0] > arr[1] ? arr[1] : arr[0];
  var highestNum = arr[0] > arr[1] ? arr[0] : arr[1];
  for(lowestNum; lowestNum <= highestNum ; lowestNum++){
    if(scm % lowestNum != 0){
      return false;
    }
  }
  return true;
}
function smallestCommons(arr) {
  var scm = false, i = 1;
  while(!scm){
  if((arr[0] * i === arr[1] * i) || (arr[0] === 1 && arr[1] === 1)){
    console.log('in if- scm', arr[0] * i);
    var divCheck = checkSequentialDivisions(arr, arr[0] * i);
    if(divCheck){
    scm = true;
    arr = arr[0] * i;
    }
  }
    i++;
  }
  
  return arr;
}


smallestCommons([1,5]);

Do you have any questions?

Yes…I just updated the question. Thanks for asking :slight_smile:

When using while it is expected for the condition to change over time, to give you a break from the loop. scm stays the same as i is 1, so arr is equivalent to arr[0], so checkSequentialDivisor function returns the same results every time. Also, if i is 1 and arr is equivalent to a[0], shouldn’t arr be an array. a[0]` does not seem one.

Thanks…I too was wondering how can I format the code in a more readable way! :smile:

I got it…the condition itself is wrong. What I did was multiplied both the numbers with same loop number and expected to be same…it cannot be true however…

Thanks guys I solved the challenge. My solution was not efficient enough.Used the algorithm described in many other solutions.


function checkSequentialDivisions(newArr, scm){
  for(var i = 2 ; i < newArr.length ; i++){
    if(scm % newArr[i] != 0){
      return false;
    }
  }
  return true;
}

function smallestCommons(arr) {
  var scm = false, i = 1;
  
  arr.sort(function(a, b){
    return b-a;
  });
  
  var newArr = [];
  for(var j = arr[0] ; j >= arr[1] ; j--){
    newArr.push(j);
  }
  
  while(!scm){
    var divCheck = checkSequentialDivisions(newArr, newArr[0] * newArr[1] * i);
    if(divCheck){
    scm = true;
    arr = newArr[0] * newArr[1] * i;
    }  
    i++;
  }
  
  return arr;
}

smallestCommons([1, 5]);