Python LCM – 2 Ways to find LCM

In this article, we’ll see different ways to find LCM in Python with program examples.

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 box.

3 thoughts on “Python LCM – 2 Ways to find LCM”

  1. Please can i get the tutorials on python. If so i will be grateful if it can be send to me.
    Thank you.

  2. please sir can you please help me the full detailed tutorials for the various programming languages, beginning with database. i really love to know how to code. i’m a young beginner

Leave a Comment

Your email address will not be published. Required fields are marked *