numpy.gcd() in Python
numpy.gcd() function computes the greatest common divisor (GCD) of two integers element-wise. The GCD of two numbers is the largest positive integer that divides both numbers without leaving a remainder.
import numpy as np
res = np.gcd(36, 60)
print(res)
Output
12
The GCD of 36 and 60 is 12, which is the largest number that divides both without leaving a remainder.
Syntax
numpy.gcd(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Parameters:
Parameter | Type | Description |
---|---|---|
x1 | array_like | First input array or integer |
x2 | array_like | Second input array or integer |
out | ndarray, optional | Optional output array to store result |
where | bool or array_like, optional | Condition array specifying where to compute |
casting | {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional | Controls data casting (default: 'same_kind') |
order | {'C', 'F', 'A', 'K'}, optional | Memory layout order of result (default: 'K') |
dtype | data-type, optional | Overrides calculation data type |
subok | bool, optional | Preserve subclasses if True |
signature | callable, optional | Internal use for generalized ufuncs |
extobj | object, optional | Internal error handling |
Returns: This function returns the element-wise greatest common divisor of x1 and x2.
Examples
Example 1: GCD Element-wise on arrays
import numpy as np
a = np.array([24, 36, 48])
b = np.array([18, 60, 72])
res = np.gcd(a, b)
print(res)
Output
[ 6 12 24]
This function computes the GCD for each corresponding pair of elements in a and b.
- GCD(24, 18) is 6
- GCD(36, 60) is 12
- GCD(48, 72) is 24
Example 2: GCD of an array and a scalar
import numpy as np
a = np.array([20, 30, 40])
res = np.gcd(a, 10)
print(res)
Output
[10 10 10]
The scalar 10 is broadcast across all elements in the array a. The GCD of 10 with each number in a is computed.
Example 3: GCD with negative numbers
import numpy as np
a = np.array([-20, -30, -40])
b = np.array([15, 25, 35])
res = np.gcd(a, b)
print(res)
Output
[5 5 5]
This function works with negative integers too and it returns the positive GCD value, as the GCD is always positive by definition.
- GCD(-20, 15) is 5
- GCD(-30, 25) is 5
- GCD(-40, 35) is 5