Help with my "Smallest Common Multiple" code

Help with my "Smallest Common Multiple" code
0

#1

Hi guys,

I’m stuck on this one. My code works with all ranges when the answer tends to be less than 150000 or so. Answers greater than that don’t work. The console gives me an error saying a possible infinite lop on line 15.

This is my code:

function smallestCommons(arr) {
var array=[];var array2=[]; 
  
arr.sort(function(a,b){
    return  b-a; 
});

  for (var i=arr[0];i>=arr[1];i--){
    array.push(i);
  }
 
  var total;
  
  for (var t=1;t<1000000;t++){
  for (var k=0;k<array.length;k++){
    if(t % array[k]==0){
      
      array2.push(t);
    }
  }
  
    if (array2.length<array.length) {
     array2=[];
   } 
  if (array2.length==array.length){
    return array2[0];
  }
    
  }
 
}

smallestCommons([1,12]);

Thanks! any feedback will be greatly appreciated. Greetings from Costa Rica!


#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

I also moved your post to the Help category, where it is better served.


#3

Thanks for the heads up and editing my post. It’s definitely easier to read.

Any advice on why the code doesn’t work?