0

function lcm(arr) {
  arr = arr.sort(function(a, b) {
    return a - b;
  });
  var j = 1;
  var num = arr[0];
  for (i = 1; i < arr.length; i++) {
    while (num % arr[i] !== 0) {
      j = j + 1;
      num = j * arr[0];
    }
    arr[0] = num;
  }
  return num;
}

console.log(lcm([3, 5, 6, 10]));

I am trying to find the least common multiple for a range of numbers in an array. The code works fine for array with two items, however the output for arrays with more than two items seems to exceed the value expected. Can anyone help me find the bug in my code ?

Thank you

Dr. Younes Henni
  • 1,613
  • 1
  • 18
  • 22
  • 2
    You need to set `j` back to `1` for each element. – Barmar Jun 23 '17 at 18:51
  • Possible duplicate of [Least common multiple for 3 or more numbers](https://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers) – Karl Reid Jun 23 '17 at 18:52
  • @KarlReid That shows lots of ways to do it, but don't really explain what he did wrong in his code. – Barmar Jun 23 '17 at 18:53
  • True. You have the real answer. I probably should have just posted that link as a comment rather than a dupe flag. – Karl Reid Jun 23 '17 at 18:54
  • Indeed I forget to set the j back to 1. Thank you all for the quick response. It was my first question on this website btw. Really appreciate. – Dr. Younes Henni Jun 23 '17 at 20:16

1 Answers1

2

Set j back to 1 each time through the loop through the array elements. Otherwise, when you process the next number, you start with a high multiplier.

// function that find the least common multiple
function lcm(arr) {
  arr = arr.sort(function(a, b) {
    return a - b;
  });
  var num = arr[0];
  for (i = 1; i < arr.length; i++) {
    var j = 1;
    while (num % arr[i] !== 0) {
      j = j + 1;
      num = j * arr[0];
    }
    arr[0] = num;
  }
  return num;
}

console.log(lcm([3, 5, 6, 10]));
Barmar
  • 741,623
  • 53
  • 500
  • 612