
Problem
Solution
Submissions
LCM of Two Numbers
Certification: Basic Level
Accuracy: 60%
Submissions: 5
Points: 10
Write a C++ program to find the least common multiple (LCM) of two positive integers.
Example 1
- Input: a = 12, b = 18
- Output: 36
- Explanation:
- Step 1: Find the GCD of 12 and 18 using Euclidean algorithm.
- Step 2: GCD(12, 18) = GCD(18, 12%18) = GCD(18, 12) = GCD(12, 18%12) = GCD(12, 6) = GCD(6, 12%6) = GCD(6, 0) = 6.
- Step 3: Calculate LCM using the formula: LCM(a,b) = (a × b) / GCD(a,b).
- Step 4: LCM(12, 18) = (12 × 18) / 6 = 216 / 6 = 36.
Example 2
- Input: a = 5, b = 7
- Output: 35
- Explanation:
- Step 1: Find the GCD of 5 and 7 using Euclidean algorithm.
- Step 2: GCD(5, 7) = GCD(7, 5%7) = GCD(7, 5) = GCD(5, 7%5) = GCD(5, 2) = GCD(2, 5%2) = GCD(2, 1) = GCD(1, 2%1) = GCD(1, 0) = 1.
- Step 3: Calculate LCM using the formula: LCM(a,b) = (a × b) / GCD(a,b).
- Step 4: LCM(5, 7) = (5 × 7) / 1 = 35 / 1 = 35.
Constraints
- 1 ≤ a, b ≤ 10^6
- Time Complexity: O(log(min(a, b))) for the Euclidean GCD algorithm
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the formula LCM(a, b) = (a * b) / GCD(a, b).
- Implement the Euclidean algorithm to compute the GCD.