Python Program to Find LCM

Posted in

Python Program to Find LCM
vinaykhatri

Vinay Khatri
Last updated on April 24, 2024

    Here we have provided a python source code that asks the user to enter 2 numbers and in Output, it prints the LCM.

    Prerequisite topics to create this Program

    • Python Input, Output
    • Python Data types
    • Python User-defined Functions
    • Python Loop

    What is LCM?

    LCM stands for Least Common Multiple, and the LCM of two numbers represents the least positive number which is the multiple of both the numbers. for example, two numbers are 3 and 6 so 6 would be their LCM because 6 is the multiple of both 3 and 6.

    Steps

    • Create a user-defined function calculate_lcm which accepts two values as arguments.
    • Using the comparison operator, we will find the largest number between the two.
    • Using the while loop we will loop till the condition (largest%num1==0 and largest%num2==0) become true.

    Python Program to Find LCM

    def calculate_lcm(a, b):
       if a > b:
           largest = a
       else:
           largest = b
    
       while(True):
           if((largest % a == 0) and (largest % b == 0)):
               lcm = largest
               break
           largest += 1
       return lcm
    
    num1 = int(input("Enter the First Number: "))
    num2 = int(input("Enter the Second Number: "))
    print("The L.C.M. of",num1,"and",num2,"is:", calculate_lcm(num1, num2))

    Output 1:

    Enter the First Number: 12
    Enter the Second Number: 16
    The L.C.M. of 12 and 16 is: 48

    Output 2:

    Enter the First Number: 1
    Enter the Second Number: 4
    The L.C.M. of 1 and 4 is: 4

    People are also reading:

    Leave a Comment on this Post

    0 Comments