lcm static method

int lcm(
  1. int a,
  2. int b
)

Calculates the Least Common Multiple (LCM) of two integers a and b.

The LCM is the smallest positive integer that is a multiple of both a and b.

This method uses the relationship: LCM(a, b) = (|a * b|) / GCD(a, b). It handles negative inputs by taking their absolute values.

Parameters:

  • a: The first integer.
  • b: The second integer.

Returns: An int representing the Least Common Multiple of a and b. Returns 0 if either a or b is 0.

Implementation

static int lcm(int a, int b) {
  if (a == 0 || b == 0) return 0;

  a = a.abs();
  b = b.abs();

  final gcdVal = gcd(a, b);
  final lcmVal = (a ~/ gcdVal) * b;

  return lcmVal;
}