find the least common multiple of two numbers in javascript

To find the least common multiple (lcm) of two numbers a and b, we first need to find their greatest common divisor (gcd) using the Euclidean algorithm. Once we have the gcd, we can use the formula:

index.tsx
lcm = (a * b) / gcd(a, b)
26 chars
2 lines

Here's a function in JavaScript that implements this algorithm:

index.tsx
function lcm(a, b) {
  // Find gcd using Euclidean algorithm
  let gcd = function(a, b) {
    return b == 0 ? a : gcd(b, a % b);
  };
  
  // Calculate lcm using gcd
  return (a * b) / gcd(a, b);
}
198 chars
10 lines

This function takes two arguments, a and b, and returns their lcm. We first define a nested function gcd that calculates the gcd using the Euclidean algorithm. We then use this function to calculate the lcm using the formula above.

Here's an example usage of the function:

index.tsx
console.log(lcm(6, 8)); // Output: 24
38 chars
2 lines

This returns 24, which is the lcm of 6 and 8.

gistlibby LogSnag