بخشی از مجموعه

Several example codes

~1 دقیقه مطالعه • بروزرسانی ۲۶ شهریور ۱۴۰۴

Program Overview

This Python program reads two integers from the user.
It calculates their Least Common Multiple (LCM) using the formula:
LCM(a, b) = |a × b| / GCD(a, b)
The gcd function from the math module is used to compute the Greatest Common Divisor.


Python Code:


import math

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

def lcm(x, y):
    return abs(x * y) // math.gcd(x, y)

result = lcm(a, b)
print("Least Common Multiple (LCM):", result)

Sample Output:


Enter the first number: 12  
Enter the second number: 18  
Least Common Multiple (LCM): 36

Explanation:

Here’s how the program works:
- It uses math.gcd() to find the greatest common divisor
- The LCM is calculated by dividing the product of the two numbers by their GCD
- The result is printed using the print() function


نوشته و پژوهش شده توسط دکتر شاهین صیامی