لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

Python Data Science NumPy ufunc LCM Lowest Common Multiple

How to find LCM (Lowest Common Multiple)?

The Lowest Common Multiple is the least number that is common multiple of both of the numbers.

Example 1: Find the LCM of the following two numbers.

Code

import numpy as np

num1 = 8
num2 = 12

x = np.lcm(num1, num2)

print(x)

the output will be

24

Returns: 24 because that is the lowest common multiple of both numbers (8*3=24 and 12*2=24).

Finding LCM in Arrays

The reduce() method is used to find the Lowest Common Multiple of all values in an array.

The reduce() method in ufunc, which in this case is the lcm() function will be used on each element to reduce the array by one dimension.

Example 2: Find the LCM of the values of the following array.

Code

import numpy as np

arr = np.array([6, 9, 12])

x = np.lcm.reduce(arr)

print(x)

the output will be

36

Returns: 36 because that is the lowest common multiple of all three numbers (6*6=36, 9*4=36 and 12*3=36).

Example 3: Find the LCM of all of an array where the array contains all integers from 1 to 5.

Code

import numpy as np

arr = np.arange(1, 5)

x = np.lcm.reduce(arr)

print(x)

the output will be

12

As you can observe that 12 is divisible by all the elements in the array 1 to 5.
Note: NumPy ufunc Universal function or ufuncs is a function which operates on ndarrays in an element by element fashion and supports array broadcasting, type casting, and many other standard features.