The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them exactly, and the Least Common Multiple (LCM) is the smallest number that both of them divide into exactly. They’re closely related: once you know the GCD, the LCM follows from a single formula.

JavaScript Program to Find GCD of Two Numbers (Euclidean Algorithm)

The Euclidean algorithm finds the GCD by repeatedly replacing the larger number with the remainder of dividing it by the smaller number, until the remainder is 0.

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

console.log(gcd(36, 24));

Output:

12


JavaScript Program to Find LCM of Two Numbers

Once you have the GCD, the LCM is simply (a * b) / gcd(a, b).

function gcd(a, b) {
  while (b !== 0) {
    [a, b] = [b, a % b];
  }
  return a;
}

function lcm(a, b) {
  return (a * b) / gcd(a, b);
}

console.log(lcm(36, 24));

Output:

72

The Euclidean algorithm runs in O(log(min(a, b))) time, which makes it far faster than the naive approach of checking every number up to the smaller of the two inputs. GCD first, then deriving LCM from it, is the standard way to solve both problems together in any language.