NumPy lcm()
The numpy.lcm()
function computes the lowest common multiple (LCM) of two input numbers or arrays element-wise.
The function operates on the absolute values of the inputs.
Syntax
</>
Copy
numpy.lcm(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x1, x2 | array_like, int | Input values or arrays. If x1.shape != x2.shape , they must be broadcastable to a common shape. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array to store the result. If None, a new array is created. |
where | array_like, optional | Condition mask for selecting elements to compute. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing LCM. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array containing the LCM of the absolute values of the inputs. If both inputs are scalars, a scalar is returned.
Examples
1. Finding LCM of Two Numbers
Computing the lowest common multiple of two integer values.
</>
Copy
import numpy as np
# Define two numbers
num1 = 12
num2 = 18
# Compute LCM
result = np.lcm(num1, num2)
# Print the result
print("LCM of", num1, "and", num2, ":", result)
Output:
LCM of 12 and 18 : 36

2. Finding LCM for Arrays of Numbers
Computing LCM for element-wise pairs in two arrays.
</>
Copy
import numpy as np
# Define two arrays
arr1 = np.array([4, 7, 12])
arr2 = np.array([5, 14, 18])
# Compute element-wise LCM
lcm_array = np.lcm(arr1, arr2)
# Print the results
print("Array 1:", arr1)
print("Array 2:", arr2)
print("LCM values:", lcm_array)
Output:
Array 1: [ 4 7 12]
Array 2: [ 5 14 18]
LCM values: [20 14 36]

3. Using the out
Parameter
Using an output array to store the LCM results instead of creating a new array.
</>
Copy
import numpy as np
# Define two arrays
arr1 = np.array([8, 15, 21])
arr2 = np.array([12, 20, 35])
# Create an output array
output_array = np.empty_like(arr1)
# Compute LCM and store result in output_array
np.lcm(arr1, arr2, out=output_array)
# Print the results
print("LCM stored in output array:", output_array)
Output:
LCM stored in output array: [24 60 105]

4. Using the where
Parameter
Computing LCM only for selected elements using a condition.
</>
Copy
import numpy as np
# Define two arrays
arr1 = np.array([6, 8, 10, 15])
arr2 = np.array([9, 12, 20, 25])
# Define a mask (compute LCM only where mask is True)
mask = np.array([True, False, True, False])
# Compute LCM where mask is True
result = np.lcm(arr1, arr2, where=mask)
# Print the results
print("LCM values with mask:", result)
Output:
LCM values with mask: [18 8 20 15]

The LCM is computed only for elements where mask=True
. Other values remain unchanged.