Tips and Tricks to Find GCD
Last Updated :
14 Oct, 2024
Improve
Let us first discuss the standard method to find GCD of two numbers a and b.
- Step 1: List all the divisors of the number ‘a’.
- Step 2: List all the divisors of the number ‘b’.
- Step 3: Identify the common divisors of both ‘a’ and ‘b’.
- Step 4: Select the largest number from the common divisors.
GCD of Two Numbers : 12 and 18
Divisors of 12 : 1, 2, 3, 4, 6 and 12
Divisors of 18 : 1, 2, 3, 6, 9 and 18
The common divisors are 1, 2, 3 and 6 and largest of these is 6 hence 6 is the GCD
How do we speed up our computations? Below are the tricks that you can use when manually computing GCD.
- gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.
- If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor.
- If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then
gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor. - If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is even
- Repeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3.