Smallest Common Multiple - help please

Smallest Common Multiple - help please
0

I am very very close here but my algorithm does not continue cycling through multiples of the largest of two numbers. Something is not compelling my function to keep looping. Any ideas?

function smallestCommons(arr) {
  
  var sorted = arr.sort((a,b)=>a-b);
  console.log(sorted);

  var multiple = sorted[1];
  //console.log(multiple);

  function checker(multiple){
  for(var i = sorted[0]; i<sorted[1]; i++){
     if(multiple%i != 0){
       return false;
       
     }
  } return true;
  }


 if(checker(multiple)){
   return multiple;
 }else{
   
multiple += sorted[1];
checker(multiple);
}




}


smallestCommons([1,5]);

The problem seems to be in the else statment of this loop:

if(checker(multiple)){
return multiple;
}else{

multiple += sorted[1];
checker(multiple);
}

you are not doing anything with the value returned from checker the second time

You say that “something is not compelling [your] function to keep looping”, but your smallestCommons function doesn’t contain a loop. You return a value if checker(multiple), but you don’t return anything in the else.

1 Like

Thanks, I think I just fixed it. Appreciate your help!

function smallestCommons(arr) {
  
  var sorted = arr.sort((a,b)=>a-b);
  console.log(sorted);

  var multiple = sorted[1];
  //console.log(multiple);

  

  function checker(multiple){
  for(var i = sorted[0]; i<sorted[1]; i++){
     if(multiple%i != 0){
       return false;
       
     }
  } return true;
  }


 while(checker(multiple)!= true){
   multiple+= sorted[1];
 }

if(checker(multiple)){
  return multiple;
}

}


smallestCommons([23, 18]);

at this point you don’t need to call again checker in the if statement, as the loop will stop only when the checkerfunction returns true, even, you don’t need the if statement at all

I think you might be mistaken here. The algorithm must return a value. Without an if statement, no value is returned.

yes, you can’t remove the return statement
My previous post still stand tho, you can remove that extra unneded check to make your algorithm that tiny bit more performing