Can we transform the two numbers

90 Views Asked by At

Given two numbers, you can replace any of them with their sum. this can be done any number of times to obtain a new pair each time.

For example, starting with (1, 3), we can get (4, 3) or (1, 4), subsequently from (4, 3) we can get (7, 3) or (4, 7) and so on.

You task is that given four numbers a, b, c, d, you have to check whether we can obtain (c, d) from pair (a, b) by performing some number of operations as defined above or not.

Sample Input.

1 3 7 3

1 3 4 5

Sample Output

Yes

No

I solved this question using BFS and was trying for a maths solution but unfortunately could not come up with a solution.

It

To explain what my BFS is doing; I'm simply trying out all the possible combinations.

int canTransformed(int a, int b, int c, int d) {
 queue<pair<int, int>> q;
q.push({a , b});
while(!q.empty()){
 int size = q.size();
    while(size--){
      auto node = q.front();
      q.pop();
      int sum = node.first + node.second;
      if(node.first == c  and node.second == d) return 1;
      if(sum <= c) q.push({sum , node.second});
      if(sum <= d) q.push({node.first , sum});
    }
}
return false;

}

For Maths: if we assume c < d and then it is very clear that we will generate some tuple like (c , somenumber) after some iterations if ax+by =c has some solution for x >=1 and y>=1; I'm not able to go beyond this..