LCM

This function computes the least common multiple (LCM) of a set of integers.

For integers a_1, a_2, \dots, a_k, the LCM is the smallest positive integer that is divisible by each input.

\operatorname{lcm}(a_1, a_2, \dots, a_k) = \min\{m \in \mathbb{N} : a_i \mid m\ \forall i\}

The function accepts a scalar or 2D range and uses all valid integer values found in the input.

Excel Usage

=LCM(integers)
  • integers (list[list], required): 2D array of integers to combine.

Returns (int): Least common multiple of the input integers.

Example 1: Least common multiple of three integers

Inputs:

integers
6 8 9

Excel formula:

=LCM({6,8,9})

Expected output:

72

Example 2: Least common multiple with zero included

Inputs:

integers
5 0 10

Excel formula:

=LCM({5,0,10})

Expected output:

0

Example 3: Least common multiple for scalar input

Inputs:

integers
15

Excel formula:

=LCM(15)

Expected output:

15

Example 4: Least common multiple from mixed 2D range

Inputs:

integers
4 x
10 20

Excel formula:

=LCM({4,"x";10,20})

Expected output:

20

Python Code

from math import lcm as math_lcm

def lcm(integers):
    """
    Compute the least common multiple of one or more integers.

    See: https://docs.python.org/3/library/math.html#math.lcm

    This example function is provided as-is without any representation of accuracy.

    Args:
        integers (list[list]): 2D array of integers to combine.

    Returns:
        int: Least common multiple of the input integers.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        values_2d = to2d(integers)
        if not isinstance(values_2d, list) or not all(isinstance(row, list) for row in values_2d):
            return "Error: Invalid input - integers must be a 2D list or scalar"

        flat_values = []
        for row in values_2d:
            for value in row:
                if isinstance(value, bool):
                    continue
                try:
                    parsed = int(value)
                    if float(value) == float(parsed):
                        flat_values.append(parsed)
                except Exception:
                    continue

        if not flat_values:
            return "Error: Input must contain at least one integer"

        result = flat_values[0]
        for value in flat_values[1:]:
            result = math_lcm(result, value)

        return int(result)
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

2D array of integers to combine.