how to find lcm in javascript

Solutions on MaxInterview for how to find lcm in javascript by the best coders in the world

showing results for - "how to find lcm in javascript"
Rameel
22 Feb 2017
1function smallestCommons(arr) {
2  // Sort the array
3  arr = arr.sort(function (a, b) {return a - b}); // numeric comparison;
4  var min = arr[0];
5  var max = arr[1];
6
7  var numbers = [];
8  var count = 0;
9
10  //Here push the range of values into an array
11  for (var i = min; i <= max; i++) {
12    numbers.push(i);
13  }
14  //Here freeze a multiple candidate starting from the biggest array value - call it j
15  for (var j = max; j <= 1000000; j+=max) {
16
17    //I increase the denominator from min to max
18    for (var k = arr[0]; k <= arr[1]; k++) {
19
20      if (j % k === 0) { // every time the modulus is 0 increase a counting 
21        count++; // variable
22      }
23    }
24
25    //If the counting variable equals the lenght of the range, this candidate is the least common value
26    if (count === numbers.length) { 
27      return j; 
28    }
29    else{
30      count = 0; // set count to 0 in order to test another candidate
31    }
32  }
33}
34
35alert(smallestCommons([1, 5]));