Python Program to Find LCM
In the following tutorial, we will learn how to find Least Common Multiple (LCM) using the Python programming language.
But before we get started, let us briefly discuss about LCM.
LCM: Least Common Multiple/ Lowest Common Multiple
LCM stands for Least Common Multiple. It is a concept of arithmetic and number system. The LCM of two integers a and b is denoted by LCM (a,b). It is the smallest positive integer that is divisible by both "a" and "b".
For example: We have two integers 4 and 6. Let's find LCM
Multiples of 4 are:
Multiples of 6 are:
Common multiples of 4 and 6 are simply the numbers that are in both lists:
LCM is the lowest common multiplier so it is 12.
Since, we have understood the basic concept of the LCM, let us consider the following program to find the LCM of given integers.
Enter first number: 3 Enter second number: 4 The L.C.M. of 3 and 4 is 12
This program stores two number in num1 and num2 respectively. These numbers are passed to the calculate_lcm() function. The function returns the LCM of two numbers.
Within the function, we have first determined the greater of the two numbers as the LCM can only be greater than or equal to the largest number. We then use an infinite while loop to go from that number and beyond.
In every iteration, we have checked if both the numbers perfectly divide the number. If so, we have stored the number as LCM and break from the loop. Otherwise, the number is incremented by 1 and the loop continues.