Python Program to find the Least Common Multiple (LCM) of two numbers

Write a Python program to find the Least Common Multiple (LCM) of two numbers provided by the user. The LCM of two numbers is the smallest number that is divisible by both.

Input-Output Examples

plaintext
Example 1:
Input:
Enter the first number: 12
Enter the second number: 15
Output: The LCM of 12 and 15 is: 60

Example 2:
Input:
Enter the first number: 9
Enter the second number: 6
Output:
The LCM of 9 and 6 is: 18

Algorithm to calculate the LCM of two numbers

  1. Start
  2. Take input: Prompt the user to enter two numbers.
  3. Find the LCM using the relationship between HCF and LCM:
    • LCM of two numbers can be calculated using the formula: LCM(x,y)=x×yHCF(x,y)LCM(x, y) = \frac{{x \times y}}{{HCF(x, y)}}LCM(x,y)=HCF(x,y)x×y​
  4. Find the HCF using the Euclidean algorithm.
  5. Calculate the LCM using the formula.
  6. Display the result.
  7. End

Python Program to calculate the LCM of two numbers

python
# Python program to find the LCM of two numbers

# Function to compute HCF using the Euclidean algorithm
def compute_hcf(x, y):
    while y != 0:
        x, y = y, x % y  # Continue until y becomes 0
    return x

# Function to compute LCM using the HCF
def compute_lcm(x, y):
    hcf = compute_hcf(x, y)
    return (x * y) // hcf  # LCM formula

# Take input from the user for two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Find the LCM of the two numbers
lcm = compute_lcm(num1, num2)

# Display the result
print(f"The LCM of {num1} and {num2} is: {lcm}")

Code Explanation

  1. Taking input from the user:
    The program uses the input() function to take two numbers from the user. The inputs are converted to integers using int().

  2. Using the Euclidean algorithm to find the HCF:
    The program first computes the HCF (or GCD) of the two numbers using the Euclidean algorithm, which is an efficient method for finding the greatest common divisor.

  3. Calculating the LCM:
    The LCM of two numbers can be calculated using the formula:

    LCM(x,y)=x×yHCF(x,y)\text{LCM}(x, y) = \frac{{x \times y}}{{\text{HCF}(x, y)}}LCM(x,y)=HCF(x,y)x×y​

    This formula is implemented in the compute_lcm() function.

  4. Displaying the output:
    The print() function is used to display the LCM of the two numbers using an f-string to format the result.

Python

1823

493

Related Articles