Given values of A and B, find the minimum positive integer value of X that can be achieved in the equation X = P*A + P*B, Here P and Q can be zero or any positive or negative integer.
Input: A = 3 B = 2 Output: 1 Input: A = 2 B = 4 Output: 2
Basically we need to find P and Q such that P*A > P*B and P*A – P*B is minimum positive integer. This problem can be easily solved by calculating GCD of both numbers.
For A = 2 And B = 4 Let P = 1 And Q = 0 X = P*A + Q*B = 1*2 + 0*4 = 2 + 0 = 2 (i. e GCD of 2 and 4) For A = 3 and B = 2 let P = -1 And Q = 2 X = P*A + Q*B = -1*3 + 2*2 = -3 + 4 = 1 ( i.e GCD of 2 and 3 )
Below is the implementation of above idea:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes