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.
classSubtractiveEuclideanGCD:
defgcd(self, a, b):
# Handle base cases for 0 and equalityif a ==0:
return b
if b ==0:
return a
if a == b:
return a
# Use the subtractive Euclidean algorithmif a > b:
return self.gcd(a - b, b)
else:
return self.gcd(a, b - a)
# Example usagesolution = SubtractiveEuclideanGCD()
print(solution.gcd(56, 98)) # Output: 14print(solution.gcd(48, 18)) # Output: 6
publicclassSubtractiveGCD {
publicintgcd(int a, int b) {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
publicstaticvoidmain(String[] args) {
SubtractiveGCD solution =new SubtractiveGCD();
System.out.println(solution.gcd(56, 98)); // Output: 14 System.out.println(solution.gcd(48, 18)); // Output: 6 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSubtractiveGCD:
defgcd(self, a, b):
while a != b:
if a > b:
a -= b
else:
b -= a
return a
# Example usagesg = SubtractiveGCD()
print(sg.gcd(56, 98)) # Output: 14print(sg.gcd(48, 18)) # Output: 6