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.
def 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))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
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.