How to Find the Lowest Common Multiple (LCM) in Python with NumPy
In this post, you’ll learn how to calculate the LCM of two numbers and even an entire array using Python and NumPy.
Program:
Finding the LCM of Two Numbers
Python’s NumPy library makes finding the LCM easy with the np.lcm() function.
num1 = 4
num2 = 6
x = np.lcm(num1, num2)
print(x)
Output:
12
Here, 12 is the smallest number that both 4 and 6 divide into evenly (4 × 3 = 12, 6 × 2 = 12).
Finding the LCM of an Array of Numbers
To compute the LCM of multiple numbers, you can use NumPy’s reduce() method along with np.lcm.
This method applies the LCM function across all elements in the array.
Program:
import numpy as np
x = np.lcm.reduce(arr)
Output:
18
LCM of Numbers from 1 to 10
Need to find the LCM of a range of numbers?
Here’s how to find the LCM of numbers from 1 to 10:
Program:
import numpy as np
arr = np.arange(1, 11)
x = np.lcm.reduce(arr)
print(x)
Output:
2520
2520 is the smallest number that is evenly divisible by all numbers from 1 to 10.