Algorithm Scripting : Lowest Common Multiple

Hello Fellow campers,
So after a dazzling 2 hours of thinking failing and thinking and and failing again, i was able to formulate a solution to solve the above challenge. After i decided to learn from freecodecamps solution and the solutions there were more confusing than mine. But solution 4 was simple and i tried to understand it but i just couldn’t. Could anyone please help me to with a simple explanation to this solution. Thanks a lot.

const smallestCommons = arr => {
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    let sol = max;
    console.log(sol)
    for (let i = max - 1; i >= min; i--) {
        console.log(i)
      if (sol % i) {
        console.log(sol += max);
        i = max;
      }
    }
   return sol;
  };

This does not actually compute the LCM. This code returns 60 for 6 and 4, but lcm(4, 6) = 12.

I have no idea what this code is actually doing.

Edit: Ah, lowest common multiple of a range. That is different than lowest common multiple.

Alrighty, here we go. Let’s walk the code.

The first thing the code does is grabs the min and max of the range. The least common multiple has to be a multiple of the biggest number in the range, so let’s guess that the solution is the first multiple of the maximum, sol = max.

How do we know if it worked? Well, lets loop through the values in the range and see if our guess is a multiple of all of the values.

If it isn’t, then we need to try the next multiple of max.

If it is, then we can exit our for loop and return the solution.

1 Like