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.



Find GCD

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:

Example: 

import numpy as npy mrx_digit = 14 ample_digit = 49 mrx_hcf = npy.gcd(mrx_digit, ample_digit) print(mrx_hcf)
Outcome: The number 7 is the largest number that can divide both numbers (14/7=2 and 49/7=7).

Calculate the HCF of 27 and 63 in the following example:

Example: 

import numpy as npy mrx_digit = 27 ample_digit = 63 mrx_hcf = npy.gcd(mrx_digit, ample_digit) print(mrx_hcf)
Outcome: The number 9 is the largest number that can divide both numbers (27/9=3 and 63/9=7).

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:

Example: 

import numpy as npy odd_arr = npy.array([9, 15, 27, 21]) mrx = npy.gcd.reduce(odd_arr) print(mrx)

Check out the greatest common denominator of the even_arr array:

Example: 

import numpy as npy even_arr = npy.array([16, 28, 24, 36, 42]) mrx = npy.gcd.reduce(even_arr) print(mrx)

Example Explanation

  • 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.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *