The Greatest Common Divisor (GCD) of two or more numbers is the largest positive number that divides each number. Python’s numpy.gcd()
method allows us to calculate the GCD of two numbers or two arrays.
numpy.gcd()
is declared as follows:
numpy.gcd (x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'gcd'>
In the syntax above, x1
and x2
are non-optional parameters, and the rest are optional.
The numpy.gcd()
method takes the following compulsory parameters:
x1
and x2
[array-like, int] - array of integer values. If the x1
and x2
are different, they must be broadcastable to a common shape for representing the output.The numpy.gcd()
method takes the following optional parameters:
out
- represents the location into which the method’s output is stored.
where
- true value indicates that
casting
- controls the type of datacasting that should occur. The same_kind option indicates that safe casting or casting within the same kind should take place.
order
- controls the memory layout order of the output function. The option K means reading the elements in the order they occur in memory.
dtype
- represents the desired data type of the array.
subok
- decides if subclasses should be made or not. If true, subclasses will be passed through.
numpy.gcd()
returns the greatest common divisor of the absolute values of the input. The return type is either ndarray
or scaler
, depending on the input type.
The examples below show the different ways numpy.gcd()
is used in Python.
The code below outputs the greatest common divisor of two numbers, 10 and 20. The result is shown below:
import numpy as npa = 10b = 20result = np.gcd(a,b)print(result)
To find the GCD of all values in a given array, the reduce()
method is used. In the code below, the reduce
method utilizes the gcd
method on each element of the array and reduces the array by one dimension. The result is shown in the code snippet below:
import numpy as nparr = np.array([8,32,36])result = np.gcd.reduce(arr)print(result)
numpy.gcd()
calculates the greatest common divisor of the elements in the same location of the two arrays and returns an array.
In the example below, the first element of arr1
is 10, and the first element of arr2
is 70. The GCD of 10 and 70 is 10. Hence, the result
array has 10 as its first element. This is shown here:
import numpy as nparr1 = np.array([10,20,35])arr2 = np.array([70,12,15])result = np.gcd(arr1,arr2)print(result)