How to find the least common multiple in JavaScript

Finding the least common multiple (LCM) is essential for fraction arithmetic, scheduling algorithms, periodic calculations, and implementing features like recurring events or synchronization systems in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented LCM calculations in components like calendar systems, scheduling tools, and mathematical utilities where finding common periods or denominators is crucial for functionality. From my extensive expertise, the most efficient approach combines the mathematical relationship LCM(a,b) = (a × b) / GCD(a,b) with the Euclidean algorithm. This method leverages the proven relationship between LCM and GCD while avoiding the computational overhead of finding all multiples.

Use the formula (a × b) / GCD(a, b) with the Euclidean algorithm for GCD.

const gcd = (a, b) => {
  while (b !== 0) {
    const temp = b
    b = a % b
    a = temp
  }
  return a
}

const lcm = (a, b) => Math.abs(a * b) / gcd(a, b)

// Usage: lcm(12, 8) returns 24, lcm(15, 25) returns 75

The LCM calculation uses the mathematical identity that LCM(a,b) × GCD(a,b) = a × b, which rearranges to LCM(a,b) = (a × b) / GCD(a,b). First, the GCD function finds the greatest common divisor using the Euclidean algorithm. Then the LCM function multiplies the two numbers and divides by their GCD. For example, LCM(12,8): GCD(12,8) = 4, so LCM = (12 × 8) / 4 = 96 / 4 = 24. The Math.abs() ensures positive results even with negative inputs. This approach is more efficient than iterating through multiples and works for any integer inputs.

Best Practice Note:

This is the same approach we use in CoreUI components for scheduling calculations, periodic operations, and mathematical utilities across our component library. Handle edge cases where one number is zero by returning zero as the LCM. For multiple numbers, use numbers.reduce(lcm) to find the LCM of an array. Consider using BigInt for very large numbers to prevent integer overflow. The algorithm provides exact results and optimal performance for practical applications requiring LCM calculations.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author