NumPy gcd()

The numpy.gcd() function computes the greatest common divisor (GCD) of two numbers or arrays element-wise.

Syntax

</>
Copy
numpy.gcd(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
x1, x2array_like, intInput values or arrays. If their shapes differ, they must be broadcastable to a common shape.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where the result is stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying where to compute GCD. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing GCD.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines if subclasses of ndarray are preserved in the output.

Return Value

Returns an array containing the GCD of the absolute values of the inputs. If both inputs are scalars, a scalar is returned.


Examples

1. Computing GCD of Two Scalar Values

Here, we compute the greatest common divisor of two integer values.

</>
Copy
import numpy as np

# Define two integer values
x1 = 48
x2 = 18

# Compute the greatest common divisor
result = np.gcd(x1, x2)

# Print the result
print("GCD of", x1, "and", x2, "is:", result)

Output:

GCD of 48 and 18 is: 6