I want to know algo for below problem

you are given 3 values say a, b and x.
you can perform 3 ops:
X-> a=a+b
Y-> a=a-b
Z-> b = a-b
now performing these ops on a and b you have to get value x in var a.
ex: a = 19, b = 7, x = 27
if you perform YZXXX on a and b you will get a = 27.

2 Likes

Please show us some of the work that you have done or started to do on this problem.You Signed up for this site 1 hour ago and expect us to start doing your homework immediately? I dont think this is going to happen here.

3 Likes

I figured this out, if all a, b, x are positive.
I will check if (k-a)%b == 0, then its possible as we will perform X operation (k-a)/b times,
otherwise we will go in 2 directions Y and Z through recursion. if a or b becomes negative , we will stop as getting a = x is not possible. I guess this should work for +ve nos. I am not able to figure out for -ve nos.

@mishraankurhdi : Let g = gcd(a,b) . A solution exists if and only if x is divisible by g .

If the solution exists , then you can find u and v such that u * a + v * b = x , by extended euclid algorithm . You can then find a series of operations once you have base values for u and v.

2 Likes

@vineetpaliwal Very well answered on scale of correctness, simplicity and giving appropriate hints(neither less, nor more).