Python Program to Find LCM – 2024

Hey guys, in this blog we will see a Python Program to Find LCM.

Example 1: Python Program to find LCM of two input numbers

# Python Program to find LCM of two input number

def compute_lcm(x, y):

   # choose the greater number
    if x > y:
        greater = x
    else:
        greater = y

    while(True):
        if((greater % x == 0) and (greater % y == 0)):
            lcm = greater
            break
        greater += 1

    return lcm

num1 = int(input("Enter the 1st number -> "))
num2 = int(input("Enter the 2nd number -> "))

print("The L.C.M. is", compute_lcm(num1, num2))

Output

Enter the 1st number -> 24
Enter the 2nd number -> 34
The L.C.M. is 408
Enter the 1st number -> 12
Enter the 2nd number -> 13
The L.C.M. is 156
Enter the 1st number -> 99
Enter the 2nd number -> 88
The L.C.M. is 792

Example 2: Program to Compute LCM Using GCD

GCD * LCM = num1 * num2

# Python program to find LCM of two input number

# This function computes GCD 
def compute_gcd(x, y):
    while(y):
        x, y = y, x % y
    return x

# This function computes LCM
def compute_lcm(x, y):
    lcm = (x*y)//compute_gcd(x,y)
    return lcm

num1 = int(input("Enter the 1st number -> "))
num2 = int(input("Enter the 2nd number -> "))

print("The L.C.M. is", compute_lcm(num1, num2))

Output

Enter the 1st number -> 45
Enter the 2nd number -> 65
The L.C.M. is 585
Enter the 1st number -> 64
Enter the 2nd number -> 55
The L.C.M. is 3520
Enter the 1st number -> 90
Enter the 2nd number -> 80
The L.C.M. is 720

Here we have simply used the following formula to calculate the LCM of the number.

GCD * LCM = num1 * num2

We have created a function compute_gcd() which returns the GCD of two numbers.

LCM = (num1*num2)/GCD

Check out our other python programming examples

Leave a Reply

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