How to Find LCM of Two Numbers in Python
The Math Behind LCM (Prime Factorization)
Lets see how Least Common Multiple (LCM) works on paper. Every whole number greater than 1 can be broken down into a unique combination of prime numbers, a rule mathematicians call the Fundamental Theorem of Arithmetic.
When you compare two numbers, their LCM is simply the smallest number that contains all the prime factors from both inputs.
Let's take 15 and 10 as an example
- Factors of 15: 3 × 5
- Factors of 10: 2 × 5
To build the LCM, we take the highest count of each prime factor that appears in either number: one 2, one 3, and one 5. Multiply those together (2 × 3 × 5), and you get 30 the smallest positive number that both 15 and 10 divide into cleanly without leaving a remainder.
Doing this with a pen and paper is straightforward for small numbers, but teaching a computer to factor massive 20-digit numbers takes far too much processing time. That is why programmers rely on remainder loops or GCD shortcuts instead of prime factorization.
LCM vs. HCF: How They Connect
LCM and the Highest Common Factor (HCF) are closely linked through the mathematical identity: a × b = HCF(a, b) × LCM(a, b). For example, multiplying 15 and 10 gives 150; dividing by their HCF of 5 immediately yields an LCM of 30, enabling rapid calculation via (a * b) // math.gcd(a, b).
Python Code: LCM Number Finder
# Python Program to find the L.C.M. of two input number hardcoded in a variable.
def compute_lcm(x, y):
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 15
num2 = 10
print("The L.C.M. is", compute_lcm(num1, num2))
Sample Output
The L.C.M. is 30
Alternative Approaches
- HCF/GCD Formula: We can use HCF/GCD formula and compute (x * y) // math.gcd(x, y) to skip iterative loops.
- Built-in libraries: We can use built in python libraries and utilize Python 3.9+'s native math.lcm(15, 10) for instant C-optimized execution.
Why Practice Writing LCM in Python?
Even though Python already includes a built-in function for this, writing an LCM finder from scratch is one of the best hands-on exercises you can do as a beginner.
Here is why it is worth your time:
- Core Logic: Building the function without any external libraries allows you to write the core logic using if-else statements, while loops, and the modulo operator (%) on your own.
- Code Optimization: Once you compare a basic step-by-step loop against the GCD formula, you can immediately see how a simple math trick can reduce thousands of unnecessary loop cycles.
- Fractions Easier: Whenever you add or subtract fractions in code, finding the Least Common Denominator is just an LCM calculation under the hood.
- Problem Solving: Exploring different ways to code the same solution teaches you how to break down problem statements and adapt your logic rather than sticking to one rigid method.
Where the Basic Loop Falls Short
The loop scripts is great when you are first learning Python, but if you drop it straight into a larger project without any adjustments, you will quickly run into a few roadblocks highlighted below:
- Slows Down Large Numbers: The loop steps forward by one on every single check, passing in two large prime numbers forces Python to run millions of iterations before finding a match.
- Zero problem: If either input is 0, Python tries to calculate greater % inside the loop and immediately crashes with a ZeroDivisionError.
- Negative Numbers: If you pass a negative number into the function, greater can start at zero or below, causing the loop to return a negative result or spin endlessly.
- Only Handles Two Numbers: As written, compute_lcm(x, y) only accepts a pair of inputs. To find the LCM of an entire list, you have to loop through the items and carry the result forward.
- Decimals Issue: LCM only applies to whole integers, so passing floating-point numbers like 12.5 leads to inaccurate remainder checks or unexpected infinite loops.
LCM in real time scenarios
Finding the Least Common Multiple isn't just a classroom math drill, it quietly powers plenty of everyday software features behind the scenes:
- Cron Job Scheduling: When one background script runs every 15 minutes and another runs every 10 minutes, developers use LCM to predict the exact moment both jobs will overlap and spike server load.
- Daily Maths: Any educational app, financial tool, or recipe scaler that adds or compares fractions like 1/15 + 1/10 relies on LCM to find the common denominator automatically.
- Hardware Synchronization: Embedded systems and network protocols use LCM to align sensors, audio sample rates, or timers running at different clock frequencies so data stays in sync.
- Inventory & Batch Packaging: E-commerce and warehouse systems use LCM to calculate the smallest order size needed when items come in fixed pack sizes such as matching boxes of 15 units with bundles of 10 without leftovers.
For more tutorials, check out the YouTube channel @programmer_script99.
Comments
Post a Comment