NumPy Ufunc GCD
Our objective in this article is to present a brief description of NumPy Ufunc GCD, its operation, and some examples of its application.
Numpy Ufunc gcd() is used to compute the greatest common divisor (GCD) of two integers.
The GCD of two integers is the largest positive integer that divides both of them without leaving a remainder.
The ufunc gcd() function in NumPy can be used to compute the GCD of two or more integers in an array.
According to Numpy Ufunc gcd, the GCD (Greatest Common Denominator), also called the HCF (Highest Common Factor), is the largest number that is a common factor between the two numbers.
In below example, compute the HCF of two numbers:
Calculate the HCF of 27 and 63 in the following example:
GCD in Arrays
You can retrieve the Highest Common Factor in an array by calling the reduce() method in Numpy Ufunc GCD.
In this case, the reduce() method will invoke a ufunc that will shrink the array by one dimension by calling the gcd() function for each item of the array.
Utilizing the odd_arr array, calculate the GCD of its items:
Check out the greatest common denominator of the even_arr array:
- In above example we have create an array named even_arr containing five even numbers.
- Then it uses the NumPy function gcd.reduce to find the greatest common divisor (GCD) of all the elements in the array.
- The reduce function applies the gcd function to all the elements in the array pairwise and returns the final result.
In this case, the GCD of all the elements in the even_arr array is 4, which is stored in the variable mrx. This is because all the numbers in the array are even and therefore divisible by 2, which is the highest common factor.