In NumPy, the numpy.gcd() function computes the greatest common divisor (GCD) of two integers element-wise in an array. The GCD is the largest positive integer that divides each of the integers without leaving a remainder. This function is part of NumPy's universal functions (ufuncs) and operates efficiently on NumPy arrays.
Here's how you can compute the GCD of elements in a NumPy array:
import numpy as np
# Define two arrays
arr1 = np.array([12, 24, 36])
arr2 = np.array([8, 16, 24])
# Compute the greatest common divisor element-wise
gcd_array = np.gcd(arr1, arr2)
print("GCD of arrays:", gcd_array) # Output: [4 8 12]
one of the inputs is zero, the GCD is calculated as the absolute value of the non-zero input. If both inputs are zero, the result is also zero.
numpy.gcd() efficiently computes the GCD using Euclid's algorithm, which recursively computes the remainder when dividing the larger number by the smaller number until the remainder becomes zero