NumPy - Finding GCD with ufunc



Finding GCD with Universal Function

NumPy provides a universal function (ufunc) called numpy.gcd() to compute the Greatest Common Divisor (GCD) of two arrays element-wise. The GCD of two integers is the largest positive integer that divides both numbers without leaving a remainder.

This function is particularly useful when working with arrays of integers where you need to find the GCD of corresponding elements.

The NumPy gcd() Function

The numpy.gcd() function is used to compute the element-wise Greatest Common Divisor of two arrays. It returns a new array containing the GCD of the corresponding elements from the input arrays.

Example

In the following example, we use the numpy.gcd() function to find the GCD of elements in two arrays −

import numpy as np

# Define two arrays
a = np.array([12, 18, 24])
b = np.array([15, 27, 36])

# Compute the element-wise GCD
gcd_result = np.gcd(a, b)

print("GCD of arrays:", gcd_result)

Following is the output obtained −

GCD of arrays: [3 9 12]

NumPy gcd() Function with Scalars

The numpy.gcd() function can also be used with scalar values to compute the GCD of two single integers. It works the same way as with arrays, returning the GCD of the given scalars.

Example

In the following example, we use the numpy.gcd() function to find the GCD of two scalar values −

import numpy as np

# Define two scalars
a = 48
b = 60

# Compute the GCD of the scalars
gcd_result = np.gcd(a, b)

print("GCD of scalars:", gcd_result)

This will produce the following result −

GCD of scalars: 12

GCD of Multi-dimensional Arrays

The numpy.gcd() function can also be applied to multi-dimensional arrays. It computes the GCD for each corresponding element in the arrays, handling arrays of any shape as long as they are broadcastable to a common shape.

Example

In the following example, we use the numpy.gcd() function to compute the GCD of two 2D arrays element-wise −

import numpy as np

# Define two 2D arrays
a = np.array([[14, 21], [35, 49]])
b = np.array([[7, 14], [21, 28]])

# Compute the element-wise GCD
gcd_result = np.gcd(a, b)

print("GCD of 2D arrays:\n", gcd_result)

The result will be as follows −

GCD of 2D arrays:
[[ 7  7]
 [ 7  7]]

The NumPy gcd.reduce() Function

The numpy.gcd.reduce() function computes the GCD of array elements along a specified axis. This is useful for finding the GCD of multiple elements within an array.

Example

In the following example, we use the numpy.gcd.reduce() function to find the GCD of all elements in an array −

import numpy as np

# Define an array
a = np.array([60, 90, 150])

# Compute the GCD of all elements
gcd_result = np.gcd.reduce(a)

print("GCD of all elements:", gcd_result)

This will produce the following result −

GCD of all elements: 30
Advertisements