
Problem
Solution
Submissions
Find GCD and LCM
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to find the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two positive integers. The GCD is the largest positive integer that divides both numbers without a remainder. The LCM is the smallest positive integer that is divisible by both numbers. Use the relationship: LCM(a, b) = (a * b) / GCD(a, b).
Example 1
- Input: a = 12, b = 18
- Output: GCD = 6, LCM = 36
- Explanation:
- Find factors of 12: 1, 2, 3, 4, 6, 12.
- Find factors of 18: 1, 2, 3, 6, 9, 18.
- Common factors are: 1, 2, 3, 6.
- The greatest common factor is 6, so GCD = 6.
- Calculate LCM using the formula: LCM = (12 * 18) / 6 = 216 / 6 = 36.
- Find factors of 12: 1, 2, 3, 4, 6, 12.
Example 2
- Input: a = 8, b = 12
- Output: GCD = 4, LCM = 24
- Explanation:
- Find factors of 8: 1, 2, 4, 8.
- Find factors of 12: 1, 2, 3, 4, 6, 12.
- Common factors are: 1, 2, 4.
- The greatest common factor is 4, so GCD = 4.
- Calculate LCM using the formula: LCM = (8 * 12) / 4 = 96 / 4 = 24.
- Find factors of 8: 1, 2, 4, 8.
Constraints
- 1 ≤ a, b ≤ 10^9
- Both numbers are positive integers
- Time Complexity: O(log(min(a, b)))
- 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 Euclidean algorithm to find GCD efficiently
- The Euclidean algorithm is based on the principle that GCD(a, b) = GCD(b, a % b)
- Continue the process until one of the numbers becomes 0
- The other number at that point is the GCD
- Calculate LCM using the relationship: LCM = (a * b) / GCD