Python Program to Find the LCM of the Array Elements

LCM of given array elements in python; Through this tutorial, i am going to show you how to find and print LCM of given array elements in python.

LCM is the lowest multiple of two or more numbers. Multiples of a number are those numbers which when divided by the number leave no remainder.

Python program to find the LCM of the array

  • Import the math module in program to find the GCD of two numbers using math.gcd() function.
  • Find the LCM of initial two numbers using: LCM(a,b) = a*b/GCD(a,b).
  • Find the LCM of three numbers with the help of LCM of first two numbers using LCM(ab,c) = lcm(lcm(a1, a2), a3). The same concept to have implemented.
# Python program to find the LCM of the array elements
# import math module
import math
# function to calculate LCM
def LCMofArray(a):
  lcm = a[0]
  for i in range(1,len(a)):
    lcm = lcm*a[i]//math.gcd(lcm, a[i])
  return lcm
# array of integers
arr1 = [1,2,3,4]
arr2 = [2,3,4,5]
arr3 = [3,4,5,6]
arr4 = [2,4,6,8,10]
arr5 = [8,4,12,40,26,28,30]
print("LCM of arr1 elements:", LCMofArray(arr1))
print("LCM of arr2 elements:", LCMofArray(arr2))
print("LCM of arr3 elements:", LCMofArray(arr3))
print("LCM of arr4 elements:", LCMofArray(arr4))
print("LCM of arr5 elements:", LCMofArray(arr5))

Output

LCM of arr1 elements: 12
LCM of arr2 elements: 60
LCM of arr3 elements: 60
LCM of arr4 elements: 120
LCM of arr5 elements: 10920

Recommended Python Tutorials

Leave a Comment