Python Program to Find LCM of Two Numbers
math.gcd() and then calculating LCM as abs(a*b) // gcd.Examples
How to Think About It
Algorithm
Code
import math def find_lcm(a, b): gcd = math.gcd(a, b) lcm = abs(a * b) // gcd return lcm # Example usage num1 = 4 num2 = 6 print(find_lcm(num1, num2))
Dry Run
Let's trace the example where a=4 and b=6 through the code
Calculate GCD
math.gcd(4, 6) returns 2
Calculate LCM
LCM = abs(4 * 6) // 2 = 24 // 2 = 12
Return LCM
Return 12 as the LCM
| Step | Operation | Value |
|---|---|---|
| 1 | GCD of 4 and 6 | 2 |
| 2 | LCM calculation abs(4*6)//2 | 12 |
| 3 | Return LCM | 12 |
Why This Works
Step 1: Find GCD first
The greatest common divisor (GCD) is the largest number that divides both inputs without remainder. We use math.gcd() to find it efficiently.
Step 2: Use relation between LCM and GCD
LCM and GCD relate by the formula LCM * GCD = |a * b|. This lets us find LCM easily once GCD is known.
Step 3: Calculate and return LCM
Divide the absolute product of the two numbers by the GCD to get the LCM, ensuring the result is positive.
Alternative Approaches
def find_lcm_loop(a, b): max_num = max(a, b) lcm = max_num while True: if lcm % a == 0 and lcm % b == 0: return lcm lcm += 1 print(find_lcm_loop(4, 6))
# This method involves finding prime factors of both numbers and combining them # It is more complex and less efficient for beginners
Complexity: O(log(min(a,b))) time, O(1) space
Time Complexity
Finding GCD using Euclid's algorithm takes O(log(min(a,b))) time, which dominates the calculation. The rest is simple arithmetic.
Space Complexity
The program uses constant extra space for variables, so space complexity is O(1).
Which Approach is Fastest?
Using math.gcd() is fastest and most efficient compared to looping or prime factorization.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using math.gcd() | O(log(min(a,b))) | O(1) | Efficient and simple for all inputs |
| Loop checking multiples | O(n) worst case | O(1) | Easy to understand but slow for large numbers |
| Prime factorization | Varies, usually slower | O(n) for factors | Educational, not practical for large inputs |
math.gcd() function to simplify LCM calculation.