π Day 41/150 – Find LCM of Two Numbers in Python
The LCM (Least Common Multiple) of two numbers is the smallest number that is divisible by both numbers.
Example:
LCM of 4 and 6 = 12
Let’s explore different ways to find LCM in Python π
πΉ Method 1 – Using Loop
a = 4
b = 6
greater = max(a, b)
while True:
if greater % a == 0 and greater % b == 0:
print("LCM:", greater)
break
greater += 1
✅ Starts from the greater number and checks multiples.πΉ Method 2 – Taking User Input
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) greater = max(a, b) while True: if greater % a == 0 and greater % b == 0: print("LCM:", greater) break greater += 1
✅ Dynamic version using user input.
πΉ Method 3 – Using GCD Formula
Formula:
LCM = (a × b) // GCD(a, b)
import math a = 4 b = 6 lcm = (a * b) // math.gcd(a, b) print("LCM:", lcm)
✅ Fastest and most efficient method.
πΉ Method 4 – Using Function
import math def find_lcm(a, b): return (a * b) // math.gcd(a, b) print(find_lcm(4, 6))
✅ Reusable and clean code.
πΉ Output
LCM: 12
π₯ Key Takeaways
✔️ LCM means smallest common multiple
✔️ Loop method is beginner-friendly
✔️ GCD formula is best for efficiency
✔️ Functions make code reusable


0 Comments:
Post a Comment