Python Lowest Common Multiple (LCM)
Find the Lowest Common Multiple (LCM) of two numbers using their HCF relation in Python.
How it Works
The Lowest Common Multiple (LCM) of two integers is the smallest positive integer that is divisible by both numbers.
There is a fundamental relation between HCF (GCD) and LCM: `LCM(a, b) = abs(a * b) // GCD(a, b)`. We can calculate LCM instantly once the GCD is known.
This calculation is much faster and less memory-intensive than iterating through multiples of the larger number.
Source Code
LCM calculator using GCD-based reduction.
lcm.py
Try in Editordef find_gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def find_lcm(a, b):
if a == 0 or b == 0:
return 0
return abs(a * b) // find_gcd(a, b)
print("LCM of 12 and 18 is:", find_lcm(12, 18))
print("LCM of 5 and 7 is: ", find_lcm(5, 7))Terminal Output
LCM of 12 and 18 is: 36
LCM of 5 and 7 is: 35Real-world Applications
- Aligning periodic background jobs and cron runs
- Fraction addition and subtraction denominators scaling
- Scheduling conflicts detection
Frequently Asked Questions
Why divide by GCD before multiplying the numbers?
Dividing first prevents potential integer overflow in languages with fixed integer sizes. While Python handles arbitrarily large integers, it is still a best practice.
More Examples
Python Highest Common Factor (HCF / GCD)
Calculate the Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm.Python Simple Calculator Script
Build a basic calculator in Python. Learn how to map mathematical operators, take user execution flows, and handle logic natively.