Finding the GCD (Greatest Common Divisor) with Python
The GCD (Greatest Common Divisor), also known as HCF (Highest Common Factor), is the largest number that can divide two or more numbers without leaving a remainder. In other words, it's the biggest number that both numbers share as a common factor.
Finding GCD of Two Numbers
Finding the GCD of two numbers in Python is simple using the NumPy library. NumPy provides a handy method called gcd() for this purpose.
Program:
import numpy as np
num1 = 6
num2 = 9
x = np.gcd(num1, num2)
print(x)
Output:
3
Here, 3 is the largest number that divides both 6 and 9 without leaving a remainder:
6 ÷ 3 = 2
9 ÷ 3 = 3
Finding GCD in an Array of Numbers
What if you want to find the GCD of multiple numbers in an array
NumPy makes this easy with the reduce() method!
The reduce() method applies the gcd() function to all elements in the array, reducing it step by step until only the GCD remains.
Program:
import numpy as np
arr = np.array([20, 8, 32, 36, 16])
x = np.gcd.reduce(arr)
print(x)
Output:
4
In this case, 4 is the largest number that can divide all the numbers in the array without a remainder.