Basically LCM is a smallest number that is divisible by both numbers (or all). Let us see how we can find lcm of two numbers in python.

1. Using Loop

First we find the larger number of two given numbers. Starting from it and will try to find the first number that is divisible by both, which is LCM.

Output:

Least common multiple =  60

In above program, first we’re finding greater number, then start a loop. Inside the loop we’ll find a number that can be divisible by both of given numbers n1 and n2. When we will get a that number we’ll store it into a new variable called lcm. If didn’t get then we’ll increase greater by 1. As we know the number will be greater than both of the numbers that why we’re start  checking lcm from greater number.

2. Using GCD

If you’ve the basic knowledge of mathematics, then you would know that we can find LCM very easily using GCD.

Also Read: Python GCD – 4 Ways to Find GCD or HCF

Here is the formula:

number 1 * number 2 =  LCM * GCD

So,

LCM  =   (number 1 * number 2)/GCD of number1 and 2

Let’s implement this formula into program.

Output

least common multiple = 60.0

So in above program we’ve have function that receives two arguments and then inside it, first we’ll find GCD and after that we’re applying given formula to find out LCM with the help of GCD and return it.

So these were two easiest ways to get the LCM of two given numbers. But what if we have more than two numbers. So here is the program for it.

How to find LCM of more than two numbers?

Output:

least common multiple =  240

So in above program, we have an list of numbers and then we will store first item of the list in variable lcm. Then we will loop through all the elements present in the list1. Inside the loop we’ll multiply lcm with i/GCD of lcm and i. So after breaking the loop we’ll get our LCM of all numbers in variable lcm.

If you’ve any problem or suggestion related to python lcm programs then please let us know in comment .