GCD

This function computes the greatest common divisor (GCD) of a set of integers.

For integers a_1, a_2, \dots, a_k, the GCD is the largest positive integer d such that d divides each input exactly.

\gcd(a_1, a_2, \dots, a_k) = \max\{d \in \mathbb{N} : d \mid a_i\ \forall i\}

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

Excel Usage

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

Returns (int): Greatest common divisor of the input integers.

Example 1: Greatest common divisor of three integers

Inputs:

integers
24 36 60

Excel formula:

=GCD({24,36,60})

Expected output:

12

Example 2: Greatest common divisor with negative input

Inputs:

integers
-27 36 45

Excel formula:

=GCD({-27,36,45})

Expected output:

9

Example 3: Greatest common divisor for scalar input

Inputs:

integers
42

Excel formula:

=GCD(42)

Expected output:

42

Example 4: Greatest common divisor from mixed 2D range

Inputs:

integers
18 x
30 48

Excel formula:

=GCD({18,"x";30,48})

Expected output:

6

Python Code

from math import gcd as math_gcd

def gcd(integers):
    """
    Compute the greatest common divisor of one or more integers.

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

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

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

    Returns:
        int: Greatest common divisor 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_gcd(result, value)

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

Online Calculator

2D array of integers to combine.