NumPy – Finding the Greatest Common Divisor (GCD)
The Greatest Common Divisor (GCD), also known as the Highest Common Factor
(HCF), is the largest positive integer that divides two or more numbers
without leaving a remainder.
Finding GCD of Two Numbers
NumPy provides a convenient function, np.gcd(), to calculate the GCD of two
numbers.
Program:
import numpy as np
num1 = 6
num2 = 9
result = np.gcd(num1, num2)
print(result)
Output:
3
Explanation:
3 is the largest number that divides both 6 and 9 without a remainder (6 ÷ 3 =
2, 9 ÷ 3 = 3).
Finding GCD in an Array
To compute the GCD of multiple numbers in an array, you can use the reduce()
method provided by NumPy's universal functions (ufuncs). It applies the GCD
function cumulatively to all elements in the array.
Program:
import numpy as np
arr = np.array([20, 8, 32, 36, 16])
result = np.gcd.reduce(arr)
print(result)
Output:
4
More topic in Numpy