Finding LCM (Lowest Common Multiple)
The Lowest Common Multiple is the smallest number that is a common multiple of two numbers.
Example
Find the LCM of the following two numbers:
import numpy as np
num1 = 4
num2 = 6
x = np.lcm(num1, num2)
print(x)
Returns:
12because that is the lowest common multiple of both numbers (43=12 and 62=12).
Finding LCM in Arrays
To find the Lowest Common Multiple of all values in an array, you can use the reduce() method.
The
reduce()method will use the ufunc, in this case thelcm()function, on each element, and reduce the array by one dimension.
Example
Find the LCM of the values of the following array:
import numpy as np
arr = np.array([3, 6, 9])
x = np.lcm.reduce(arr)
print(x)
Returns:
18because that is the lowest common multiple of all three numbers (36=18, 63=18 and 92=18).
Example
Find the LCM of all values of an array where the array contains all integers from 1 to 10:
import numpy as np
arr = np.arange(1, 11)
x = np.lcm.reduce(arr)
print(x)