34.LCM in Python | Easy Trick with GCD
Learn how to find the **Least Common Multiple (LCM)** of two numbers in Python using the **Euclidean Algorithm**. We’ll use the formula: LCM(a,b)=GCD(a,b)/ (a×b) This trick is super useful for **coding interviews, competitive programming, and math problems**. Code Used in Video def gcd(a, b): while b != 0: a, b = b, a % b return a def lcm(a, b): return abs(a * b) // gcd(a, b) # Examples print(lcm(4, 6)) # 12 print(lcm(15, 20)) # 60 print(lcm(21, 6)) # 42 Step-by-Step Explanation 1️⃣ **GCD function** → Uses Euclidean Algorithm (repeat `a, b = b, a % b` until `b = 0`). 2️⃣ **LCM formula** → `(a × b) ÷ GCD(a, b)` ensures smallest common multiple. 3️⃣ **Examples** → `LCM(15, 20) = 60`, `LCM(21, 6) = 42`. --- ### 🧮 Example Dry Run * Input: `LCM(15, 20)` * GCD = 5 * (15 × 20) ÷ 5 = 60 ✅ LCM = 60 --- Real-Life Uses of LCM * Scheduling tasks (traffic lights, work shifts). * Repeating cycles in math and science. * Simplifying fractions and ratios. #Python #LCM #CodingInterview #Math #EuclideanAlgorithm #PythonForBeginners #DSA
Download
0 formatsNo download links available.