Maximum GCD of two numbers possible by adding same value to them
Given two numbers A and B, the task is to find the maximum Greatest Common Divisors(GCD) that can be obtained by adding a number X to both A and B.
Input: A = 1, B = 5
Explanation: Adding X = 15, the obtained numbers are A = 16 and B = 20. Therefore, GCD of A, B is 4.
Input: A = 2, B = 23
Approach: This problem can be solved in a very optimized manner using the properties of Euclidean GCD algorithm. Follow the steps below to solve the problem:
- If a > b: GCD(a, b)= GCD(a – b, b). Therefore, GCD(a, b) = GCD(a – b, b).
- On adding x to A, B, gcd(a + x, b + x) = gcd(a – b, b + x). It can be seen that (a – b) remains constant.
- It can be safely said that the GCD of these numbers will never exceed (a – b). Since (b + x) can be made a multiple of (a – b) by adding a possible value of x.
- Therefore, it can be concluded that GCD remains (a – b).
Below is the implementation of the above approach.
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.