Smallest common multiple need help

Smallest common multiple need help
0.0 0

#1

Could you please help why this code have an infinite loop?

function smallestCommons(arr) {
  var lst = [];
  for (var m = Math.min(arr[0], arr[1]); m <= Math.max(arr[0], arr[1]); m++) {
    lst.push(m);
  }
  
  var i = lst.reduce(function(a,b){return a*b;});
  var k = lst.reduce(function(a,b){return a*b;});
  while (i > 1) {
    for (var j = lst[0]; j <= lst[lst.length-1]; j++) {

      if (i%j !== 0) {
        break;
      } else {
        k = i;
      }
    }
    i--;
  }
  return k;
}

#2

Please give a test case that creates an infinite loop


#3

smallestCommons([6, 12]) for example


#4

That terminates and returns 2991684


#5

Then why I get an error each and every time?


#6

Add this as the first line in the code window

// noprotect

and run - if there is an infinite loop you can always kill the tab with Chrome Task Manager (shift-esc)


#7

The same problem. Infinite loop. Checked several times


#8

I copy-pasted your code as-is in a chrome devtools snippet - it runs fine and terminates - can you try the same? It may be a problem in the environment of the exercise tab


#9

Could you please tell how can I access it? I don’t have any idea what is chrome devtools snippet


#10

https://developers.google.com/web/tools/chrome-devtools/snippets


#11

Thank you!
But I run the same code and got 6 not the answer that you posted.


#12

I’ve tried the code using Chrome and Safari, and neither triggers the infinite loop warning. Keep in mind that this is a precaution and it doesn’t mean your code is actually running in an infinite loop. Try refreshing your browser.


#13

yes - 6 is right - I pasted the wrong value - the code does run and return a value - I think on the exercise page the test case smallestCommons([1,13]) is very slow because i is 6227020800 and the nested loop takes so long it seems an infinite loop though it does eventually terminate - you should improve your solution