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 4th multiple of 12 and 48 is 1st 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, we will use a mathematical formula which is:

    Multiple of n numbers=LCM of n numbers* (HCF of the n number)^(n-1).

Algorithm to find the LCM of array elements

  • Import the math module in the program.
  • Take the elements of an array from the user.
  • Find the HCF of the elements of the array by using the GCD function from the math module.
  • Also, find the multiple of each element of the given array and assign it in a variable.
  • By using the above formula just find the LCM of the elements of the given array and assign it to a new variable P.
  • Print the value of variable P which is the LCM of the array's elements.

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

Program:

# importing the module
import math

# array of integers
A=[8,4,12,40,26,28]

# initialize variable b as first element of A.
b=A[0]
m=1

for j in range(1,len(A)):
    s=math.gcd(b,A[j])
    b=s
    
for k in A:
    m=m*k
p=m//(b**(len(A)-1))

print("GCD of array's element:",b)
print("LCM of array's element:",p)

Output

GCD of array's element: 2
LCM of array's element: 349440






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.