Smallest Common Multiple - some Help

*What is the problem in my code?

Your code so far


function smallestCommons(arr) {
  var newArr = [];
  var max = Math.max(arr[0],arr[1]);
  var min = Math.min(arr[0],arr[1]);
  for (var i = min; i <= max; i++) { 
    newArr.push(i)
  }
  newArr = newArr.reverse();

  var commonMultiple = newArr.reduce((x,y) => x*y);
  newArr.map(function(x) {

    if(newArr.every(function(y) {

      return (commonMultiple / y) % x == 0;
    })) {
      commonMultiple = commonMultiple / x;
      console.log(commonMultiple);

    }
  })
  return commonMultiple;
}

smallestCommons([23, 18]);

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple

smallestCommons([1, 5]) should return a number.
Passed

smallestCommons([1, 5]) should return 60.
Passed

smallestCommons([5, 1]) should return 60.
Passed

smallestCommons([2, 10]) should return 2520.
Passed

smallestCommons([1, 13]) should return 360360.
Passed

smallestCommons([23, 18]) should return 6056820.
Not passed

This is a really odd way to do it imo, the use of map and every isn’t particularly idiomatic and quite hard to read, usually a map is over a pure function, and not one which mutates state, perhaps you meant to use a forEach instead?

The main problem is actually most likely the running time of your algorithm, it’s quite inefficient, checking many possibilities.

As a hint for what you should consider trying to reduce the complexity, the lowest common multiple of a set of numbers, LCM(a, b, c, d, ...) is equal to the lowest common multiple in pairs as follows:

LCM(a, b, c, d, ...) = LCM(..., LCM(d, LCM(c, LCM(a, b)))

Which is the exact form needed for a reduce, once you can find the lowest common multiple of two numbers!

Also there’s a great way to find the LCM via the GCD, check the wikipedia article for that and then consider implementing one of the classic algorithms for the greatest common denominator

Happy hacking!

I solved it. Thank you!

my solution:

function smallestCommons(arr) {
  var max = Math.max(...arr);
  var min = Math.min(...arr);
  function gdc (x,y) {
    return y ? gdc (y , x%y) : x;
  }

  function lcm (x,y) {
    return (x*y) / gdc(x,y);
  }

  var newArr = [];
  for (var i = min; i <= max;i++) {
    newArr.push(i);
  }
  console.log(newArr);

var lcm = newArr.reduce((x,y) => lcm(x,y));

return lcm;

}


smallestCommons([1,5]);```

Don’t forget to wrap your solution in spoiler tags [spoiler]Spoils here[/spoiler].