LCM of Two Numbers (Loop)
Compute the least common multiple (LCM) of two integers using GCD.
BeginnerTopic: Loop Programs
Python LCM of Two Numbers (Loop) Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to find LCM of two numbers using GCD
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
orig_a, orig_b = a, b
while b != 0:
a, b = b, a % b
gcd = abs(a)
lcm = abs(orig_a * orig_b) // gcd if gcd != 0 else 0
print("LCM is", lcm)Output
Enter first integer: 12 Enter second integer: 18 LCM is 36
Understanding LCM of Two Numbers (Loop)
We first find GCD with the Euclidean algorithm, then use the identity LCM(a, b) = |a × b| / GCD(a, b).
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.