NumPy LCM Lowest Common Multiple

🔢 NumPy LCM (Lowest Common Multiple)

NumPy provides a fast and vectorized function np.lcm() to compute the lowest common multiple of integers element-wise.


✅ 1. Basic LCM of Two Numbers

import numpy as np

a = 12
b = 15

lcm = np.lcm(a, b)
print(lcm) # 60

  • LCM of 12 and 15 is 60 → smallest number divisible by both


✅ 2. LCM of Arrays

arr1 = np.array([4, 6, 8])
arr2 = np.array([10, 9, 12])

lcm_arr = np.lcm(arr1, arr2)
print(lcm_arr) # [20 18 24]

  • Computes element-wise LCM

  • lcm_arr[i] = LCM(arr1[i], arr2[i])


✅ 3. LCM with Scalars and Arrays

arr = np.array([5, 10, 15])
scalar = 20

lcm_arr = np.lcm(arr, scalar)
print(lcm_arr) # [20 20 60]

  • Scalar is broadcasted to array automatically


✅ 4. Using LCM for Multiple Numbers

  • NumPy lcm works element-wise. For multiple numbers, you can use reduce:

arr = np.array([4, 6, 8])
overall_lcm = np.lcm.reduce(arr)
print(overall_lcm) # 24
  • Computes LCM of all elements in the array


✅ 5. Notes & Tips

  • LCM is always ≥ max(a, b)

  • Useful in fractions, synchronization, scheduling, or cyclic events

  • Works with integers only


🎯 Practice Exercises

  1. Find the LCM of 18 and 24.

  2. Find element-wise LCM of arrays [3,4,5] and [6,8,10].

  3. Find the LCM of [4, 6, 8, 12] using np.lcm.reduce().

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *