
Problem
Solution
Submissions
GCD of two numbers
Certification: Basic Level
Accuracy: 30%
Submissions: 10
Points: 5
Write a C# program to implement the FindGCD(int a, int b) function, which finds the greatest common divisor (GCD) of two integers. The GCD of two integers is the largest positive integer that divides both numbers without a remainder.
Algorithm
- Step 1: Use the Euclidean algorithm to find the GCD.
- Step 2: If one of the numbers is zero, return the other number (as the GCD of any number and 0 is the number itself).
- Step 3: Otherwise, recursively call the function with b and a % b until one of the numbers becomes zero.
Example 1
- Input: a = 56, b = 98
- Output: 14
- Explanation:
- Using the Euclidean algorithm:
- - Step 1: 98 = 56 × 1 + 42
- - Step 2: 56 = 42 × 1 + 14
- - Step 3: 42 = 14 × 3 + 0
- Since the remainder becomes 0, the GCD is 14.
Example 2
- Input: a = 17, b = 23
- Output: 1
- Explanation:
- Using the Euclidean algorithm:
- - Step 1: 23 = 17 × 1 + 6
- - Step 2: 17 = 6 × 2 + 5
- - Step 3: 6 = 5 × 1 + 1
- - Step 4: 5 = 1 × 5 + 0
- Since the remainder becomes 0, the GCD is 1.
- This means 17 and 23 are coprime (their only common divisor is 1).
Constraints
- 1 ≤ a, b ≤ 10^9
- Time Complexity: O(log(min(a, b)))
- Space Complexity: O(log(min(a, b))) for recursive approach, O(1) for iterative approach
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
- Implement the Euclidean algorithm which states that gcd(a, b) = gcd(b, a % b)
- You can implement this recursively or iteratively
- Remember to handle the base case when one of the numbers becomes zero
- For large numbers, an iterative solution may be preferred to avoid stack overflow