In the subtractive Euclidean algorithm, instead of repeatedly dividing and taking the remainder, we continually subtract the smaller number from the larger number until they become equal. This equal number is the GCD.
Approach
Here is the approach:
- Subtract the smaller number from the larger number repeatedly.
- Continue until both numbers become equal.
- The result is the GCD.
Solutions
Method 1- Recursive
Code
Java
public class SubtractiveEuclideanGCD {
public int gcd(int a, int b) {
// Handle base cases for 0 and equality
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
if (a == b) {
return a;
}
// Use the subtractive Euclidean algorithm
if (a > b) {
return gcd(a - b, b);
} else {
return gcd(a, b - a);
}
}
public static void main(String[] args) {
SubtractiveEuclideanGCD solution = new SubtractiveEuclideanGCD();
System.out.println(solution.gcd(56, 98)); // Output: 14
System.out.println(solution.gcd(48, 18)); // Output: 6
}
}
Python
class SubtractiveEuclideanGCD:
def gcd(self, a, b):
# Handle base cases for 0 and equality
if a == 0:
return b
if b == 0:
return a
if a == b:
return a
# Use the subtractive Euclidean algorithm
if a > b:
return self.gcd(a - b, b)
else:
return self.gcd(a, b - a)
# Example usage
solution = SubtractiveEuclideanGCD()
print(solution.gcd(56, 98)) # Output: 14
print(solution.gcd(48, 18)) # Output: 6
Complexity
- ⏰ Time complexity:
O(max(a, b))
in the worst case because it involves linear subtraction. - 🧺 Space complexity:
O(max(a, b))
due to the recursive calls on the stack, as each call reduces only one of the numbers slightly.
Method 2 - Iterative
Code
Java
public class SubtractiveGCD {
public int gcd(int a, int b) {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
public static void main(String[] args) {
SubtractiveGCD solution = new SubtractiveGCD();
System.out.println(solution.gcd(56, 98)); // Output: 14
System.out.println(solution.gcd(48, 18)); // Output: 6
}
}
Python
class SubtractiveGCD:
def gcd(self, a, b):
while a != b:
if a > b:
a -= b
else:
b -= a
return a
# Example usage
sg = SubtractiveGCD()
print(sg.gcd(56, 98)) # Output: 14
print(sg.gcd(48, 18)) # Output: 6
Complexity
- ⏰ Time complexity:
O(max(a, b))
in the worst case because it involves linear subtraction. - 🧺 Space complexity:
O(1)
as it uses constant space.