Home » Python » Python programs

# Python program to find the LCM of the array elements

Here, we will learn **how to find the LCM (lowest common multiple) of the arrays elements in the Python programming language?**

Submitted by Bipin Kumar, on November 19, 2019

**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. When we are talking about the multiple, we consider only the positive number. For example, the **LCM of 12 and 48 is 48** because **48** is 4^{th} multiple of **12** and **48** is 1^{st} multiple of **48**. Here, an array of positive elements will be provided by the user and we have to **find the LCM of the elements of the array by using the Python**. To **find LCM of the elements of the array**, use the following algo,

**Algorithm to find the LCM of array elements**

- We need to import the math module to find the GCD of two numbers using math.gcd() function.
- At first, find the LCM of initial two numbers using:
**LCM(a,b) = a*b/GCD(a,b)**. And, then 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 we have implemented.

Now, we will write the Python program in a simple way by implementing the above algorithm.

**Program:**

# importing the 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] arr2 = [2,3,4] arr3 = [3,4,5] arr4 = [2,4,6,8] arr5 = [8,4,12,40,26,28] 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: 6 LCM of arr2 elements: 12 LCM of arr3 elements: 60 LCM of arr4 elements: 24 LCM of arr5 elements: 10920

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions