NumPy ufunc LCM and GCD
NumPy's gcd and lcm ufuncs compute greatest common divisors and least common multiples element-wise, and their reduce() methods extend the same idea across an entire array at once.
Greatest Common Divisor with np.gcd()
np.gcd(a, b) returns the largest integer that divides both a and b evenly. Applied to arrays, it works element-wise, computing the GCD of each corresponding pair of values.
Example
import numpy as np
# GCD of a single pair
print(np.gcd(12, 18))
# 6
# GCD applied element-wise across two arrays
a = np.array([12, 20, 45])
b = np.array([18, 30, 60])
print(np.gcd(a, b))
# [ 6 10 15]Least Common Multiple with np.lcm()
np.lcm(a, b) returns the smallest positive integer that is a multiple of both a and b. It is related to gcd by the identity lcm(a, b) = abs(a * b) / gcd(a, b), and like gcd it broadcasts element-wise across arrays.
Example
import numpy as np
# LCM of a single pair
print(np.lcm(4, 6))
# 12
# LCM applied element-wise across two arrays
a = np.array([4, 6, 9])
b = np.array([6, 8, 12])
print(np.lcm(a, b))
# [12 24 36]Reducing an Entire Array with reduce()
Every NumPy ufunc that takes two arguments has a .reduce() method, which applies the ufunc cumulatively across all the elements of a single array. np.gcd.reduce(arr) finds the GCD shared by every value in arr, and np.lcm.reduce(arr) finds the LCM of them all.
Example
import numpy as np
numbers = np.array([12, 18, 24])
# GCD of every element in the array combined
print(np.gcd.reduce(numbers))
# 6
# LCM of every element in the array combined
print(np.lcm.reduce(numbers))
# 72
# Practical use: find when three repeating cycles next align
periods = np.array([4, 6, 10])
print(np.lcm.reduce(periods))
# 60- np.gcd() is useful for simplifying fractions: dividing both numerator and denominator by their GCD reduces the fraction to lowest terms.
- np.lcm() is useful for scheduling problems, such as finding when repeating cycles of different lengths next line up.
- Every two-argument NumPy ufunc has a .reduce() method that applies the ufunc cumulatively across all elements of a single array.
- np.gcd.reduce() and np.lcm.reduce() generalize the pairwise gcd/lcm functions to work on three or more numbers at once.
Exercise: NumPy ufunc LCM and GCD
What does np.gcd(x1, x2) compute?