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
| Parameter | Type | Description |
|---|---|---|
x1, x2 | array_like, int | Input values or arrays. If their shapes differ, they must be broadcastable to a common shape. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where the result is stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying where to compute GCD. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing GCD. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines 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
