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.
x=12 y=20 if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater = greater + 1 print ("Least common multiple = ", 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.
import math def get_lcm(n1,n2): #find gcd gcd = math.gcd(n1,n2) #formula result = (n1*n2)/gcd return result n1 = 12 n2 = 20 lcm = get_lcm(n1,n2) print("least common multiple = ", lcm)
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?
from math import gcd list1 = [12,48,8,60] lcm = list1[0] for i in list1[1:]: lcm = int(lcm*i/gcd(lcm, i)) print("least common multiple = ", lcm)
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.
The post Python LCM – 2 Ways to find LCM appeared first on The Crazy Programmer.
from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/05/python-lcm-2-ways-to-find-lcm.html
Comments
Post a Comment