Java Program to Compute GCD
GCD (Greatest Common Divisor) of two given numbers A and B is the highest number that can divide both A and B completely, i.e., leaving remainder 0 in each case. GCD is also called HCF(Highest Common Factor). There are various approaches to find the GCD of two given numbers.
The GCD of the given two numbers A and B can be calculated using different approaches.
- General method
- Euclidean algorithm (by repeated subtraction)
- Euclidean algorithm (by repeated division)
Input: 20, 30 Output: GCD(20, 30) = 10 Explanation: 10 is the highest integer which divides both 20 and 30 leaving 0 remainder Input: 36, 37 Output: GCD(36, 37) = 1 Explanation: 36 and 37 don't have any factors in common except 1. So, 1 is the gcd of 36 and 37
Note: gcd(A, B) = 1 if A, B are co-primes.
In the general approach of computing GCD, we actually implement the definition of GCD.
- First, find out all the factors of A and B individually.
- Then list out those factors which are common for both A and B.
- The highest of those common factors is the GCD of A and B.
A = 20, B = 30 Factors of A : (1, 2, 4, 5, 10, 20) Factors of B : (1, 2, 3, 5, 6, 10, 15, 30) Common factors of A and B : (1, 2, 5, 10) Highest of the Common factors (GCD) = 10
It is clear that the GCD of 20 and 30 can’t be greater than 20. So we have to check for the numbers within the range 1 and 20. Also, we need the greatest of the divisors. So, iterate from backward to reduce computation time.
GCD = 10
Euclidean algorithm (repeated subtraction):
This approach is based on the principle that the GCD of two numbers A and B will be the same even if we replace the larger number with the difference between A and B. In this approach, we perform GCD operation on A and B repeatedly by replacing A with B and B with the difference(A, B) as long as the difference is greater than 0.
A = 30, B = 20 gcd(30, 20) -> gcd(A, B) gcd(20, 30 - 20) = gcd(20,10) -> gcd(B,B-A) gcd(30 - 20, 20 - (30 - 20)) = gcd(10, 10) -> gcd(B - A, B - (B - A)) gcd(10, 10 - 10) = gcd(10, 0) here, the difference is 0 So stop the procedure. And 10 is the GCD of 30 and 20
GCD = 10
Euclidean algorithm (repeated division):
This approach is similar to the repeated subtraction approach. But, in this approach, we replace B with the modulus of A and B instead of the difference.
A = 30, B = 20 gcd(30, 20) -> gcd(A, B) gcd(20, 30 % 20) = gcd(20, 10) -> gcd(B, A % B) gcd(10, 20 % 10) = gcd(10, 10) -> gcd(A % B, B % (A % B)) gcd(10, 10 % 10) = gcd(10, 0) here, the modulus became 0 So, stop the procedure. And 10 is the GCD of 30 and 20
GCD = 10
Euclid’s repeated division approach is most commonly used among all the approaches.