What is LCM? | Maths Explanation for Python Kids
                        Akin to finding H.C.F., L.C.M. is commonly found by repeated factorisation.
                        Only this time, the factors do not have to be common amongst the set of numbers.
                        
                        If we have the set of numbers 8, 12 and 
                        18 for example, their L.C.M. is found thus:
                    
Hence, L.C.M. of 8, 12 and 18 = 2 X 2 X 2 x 3 x 3 = 72
Step-by-Step Guide to L.C.M. by Factorisation in Python
We shall follow the steps below in writing our Python LCM code.
Step 1:
Do a numerical reverse sort on the (resulting) set so its first member is the largest in the set.
Step 2:
Starting with 2, iteratively check through the set of numbers for individual factors.
Step 3:
For each individual factor, divide affected member(s) of the number set by the factor.
Step 4:
Repeat the above steps recursively until there are no more individual factors.
                        Create a new Python class file; File, New File.
                        Call it FindLCM.py
                        Type out the adjoining Python code for finding Lowest Common Multiple (L.C.M.)
                    
Note: You can comment out the Python code for the main class from the previous lesson if you have been following.
So! Python Fun Practice Exercise - Find LCM
As a fun practice exercise, feel free to try out your own numbers, and see how the Python code finds the LCM of those numbers.
Python Code for Find LCM - Module File.
class findLCM:
# A constructor
def __init__(self, group):
self.set_of_numbers = []
for member in group:
self.set_of_numbers.append(member)
# Sort array in descending order
self.set_of_numbers.sort(reverse=True)
self.all_factors = []
self.index = 1
self.state_check = False
self.calc_result = 1
def findLCMFactors(self):
# Copy 'set_of_numbers' into 'arg_copy'
self.arg_copy = []
for number in self.set_of_numbers:
self.arg_copy.append(number)
# STEP 1:
# sort in descending order
self.arg_copy.sort(reverse=True)
while self.index <= self.arg_copy[0]:
self.state_check = False
for count in range(len(self.set_of_numbers)):
if self.set_of_numbers[count] % self.index == 0:
# STEP 3:
self.set_of_numbers[count] /= self.index
if self.state_check == False:
self.all_factors.append(self.index)
self.state_check = True # do not store the factor twice
# STEP 4:
if self.state_check: return self.findLCMFactors()
self.index += 1
return None
# Returns an array reference of the desired set of even numbers
def getLCM(self):
# STEP 2:
self.index = 2
self.findLCMFactors()
# iterate through and retrieve members
for factor in self.all_factors:
self.calc_result *= factor
return self.calc_result
Python Code for Find LCM - Main Class.
from LCM import findLCM
# Use the LCM module/class
group = [2, 3, 4]
lcm = findLCM(group)
answer = lcm.getLCM()
print("The L.C.M. of ", group, " is", answer, "\n")