ufunc Finding LCM
The lowest common multiple (LCM), also called the least common multiple, of two integers is the smallest positive number that both divide evenly. The LCM of 4 and 6 is 12: the multiples of 4 are 4, 8, 12, 16, …; the multiples of 6 are 6, 12, 18, …; 12 is the first they share.
LCMs answer "when do things line up again?" questions: two buses leaving every 4 and 6 minutes depart together every 12 minutes.
LCM of two numbers
np.lcm(a, b) is a ufunc, so it works on scalars and arrays alike:
import numpy as np
print(np.lcm(4, 6))
print(np.lcm(7, 5)) # coprime numbers: LCM is their product
print(np.lcm(12, 18))12
35
36
Element-wise LCM of arrays
import numpy as np
a = np.array([3, 8, 10, 9])
b = np.array([4, 12, 15, 6])
print(np.lcm(a, b))
# Broadcasting: LCM of each number with 6
print(np.lcm(np.arange(1, 9), 6))[12 24 30 18]
[ 6 6 6 12 30 6 42 24]
LCM of a whole array: reduce
To find the LCM of more than two numbers, apply it repeatedly: lcm(a, b, c) = lcm(lcm(a, b), c). The ufunc method reduce does exactly that:
import numpy as np
numbers = np.array([4, 6, 10])
print(np.lcm.reduce(numbers))
# The smallest number divisible by every integer from 1 to 10
print(np.lcm.reduce(np.arange(1, 11)))60
2520
np.lcm.accumulate shows the intermediate results, which helps to understand how reduce works:
import numpy as np
print(np.lcm.accumulate(np.array([4, 6, 10, 7])))[ 4 12 60 420]
Example: planning repeating events
Three maintenance tasks repeat every 6, 8 and 15 days. They are all done today. When will all three fall on the same day again, and when does each pair coincide?
import numpy as np
periods = np.array([6, 8, 15])
names = ["oil", "filter", "inspection"]
print("all three together every", np.lcm.reduce(periods), "days")
for i in range(3):
for j in range(i + 1, 3):
print(f"{names[i]} + {names[j]}: every {np.lcm(periods[i], periods[j])} days")all three together every 120 days
oil + filter: every 24 days
oil + inspection: every 30 days
filter + inspection: every 120 days
Adding fractions
The LCM of the denominators is the common denominator you need to add fractions by hand:
import numpy as np
num = np.array([1, 3, 5])
den = np.array([4, 10, 6]) # 1/4 + 3/10 + 5/6
common = np.lcm.reduce(den)
scaled = num * (common // den)
print(f"{' + '.join(f'{n}/{common}' for n in scaled)} = {scaled.sum()}/{common}")15/60 + 18/60 + 50/60 = 83/60
Note:
np.lcmonly works with integers. Passing floats such as4.0raises aTypeError; convert with.astype(int)first. For very large results, beware of integer overflow.
Test yourself
What is np.lcm(6, 10)?
- 2
- 16
- 30
- 60
How do you compute the LCM of all elements of an array a?
- np.lcm(a)
- np.lcm.reduce(a)
- np.lcm.sum(a)
- np.lcm.all(a)
What is the LCM of two coprime numbers such as 8 and 9?
- 1
- 17
- 72
- 9