
Problem
Solution
Submissions
GCD of Two Numbers
Certification: Basic Level
Accuracy: 80%
Submissions: 5
Points: 5
Write a C++ program that finds the Greatest Common Divisor (GCD) of two positive integers using the Euclidean algorithm.
Example 1
- Input: a = 48, b = 18
- Output: 6
- Explanation:
- Step 1: Apply the Euclidean algorithm: gcd(a, b) = gcd(b, a % b) until b becomes 0.
- Step 2: gcd(48, 18) = gcd(18, 48 % 18) = gcd(18, 12).
- Step 3: gcd(18, 12) = gcd(12, 18 % 12) = gcd(12, 6).
- Step 4: gcd(12, 6) = gcd(6, 12 % 6) = gcd(6, 0).
- Step 5: When b becomes 0, the GCD is the value of a, which is 6.
Example 2
- Input: a = 13, b = 7
- Output: 1
- Explanation:
- Step 1: Apply the Euclidean algorithm: gcd(a, b) = gcd(b, a % b) until b becomes 0.
- Step 2: gcd(13, 7) = gcd(7, 13 % 7) = gcd(7, 6).
- Step 3: gcd(7, 6) = gcd(6, 7 % 6) = gcd(6, 1).
- Step 4: gcd(6, 1) = gcd(1, 6 % 1) = gcd(1, 0).
- Step 5: When b becomes 0, the GCD is the value of a, which is 1.
Constraints
- 1 ≤ a, b ≤ 10^9
- Both inputs 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
- The Euclidean algorithm states that gcd(a, b) = gcd(b, a % b)
- Use recursion or iteration to implement the algorithm
- The base case is when the second number becomes 0, then the GCD is the first number