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

2. Computing GCD for Arrays of Values

We compute the GCD element-wise for two NumPy arrays.

</>
Copy
import numpy as np

# Define two arrays of integers
x1 = np.array([12, 15, 21, 30])
x2 = np.array([8, 25, 14, 10])

# Compute the element-wise GCD
gcd_values = np.gcd(x1, x2)

# Print the results
print("Array 1:", x1)
print("Array 2:", x2)
print("GCD values:", gcd_values)

Output:

Array 1: [12 15 21 30]
Array 2: [ 8 25 14 10]
GCD values: [4 5 7 10]

3. Using the out Parameter

Using an output array to store results instead of creating a new array.

</>
Copy
import numpy as np

# Define two arrays of integers
x1 = np.array([20, 50, 100])
x2 = np.array([30, 75, 25])

# Create an output array with the same shape
output_array = np.empty_like(x1)

# Compute GCD and store the result in output_array
np.gcd(x1, x2, out=output_array)

# Print the results
print("Computed GCD values:", output_array)

Output:

Computed GCD values: [10 25 25]

4. Using the where Parameter

Using a condition to compute GCD only for selected elements.

</>
Copy
import numpy as np

# Define two arrays of integers
x1 = np.array([24, 35, 40, 18])
x2 = np.array([16, 25, 30, 9])

# Define a mask (compute GCD only where mask is True)
mask = np.array([True, False, True, False])

# Compute GCD values where mask is True
result = np.gcd(x1, x2, where=mask)

# Print the results
print("Computed GCD values with mask:", result)

Output:

Computed GCD values with mask: [ 8  0 10  0]

The GCD values are computed only for elements where mask=True. The other values remain unchanged.