


You are given two integers ‘X’ and ‘Y’. You can convert the number ‘X’ into another integer ‘Y’ using the following two operations in any order.
i) Multiply ‘X’ by 2
ii) Subtract 1 from ‘X’
Your task is to find the minimum number of operations needed to convert ‘X’ into ‘Y’.
Note: It is always possible to convert ‘X’ into ‘Y’
The first line of the input contains ‘T’ denoting the number of test cases.
The first line of each test case contains the two integers ‘X’ and ‘Y’.
Output Format:
For each test case, print a single line containing a single integer denoting the minimum number of operations needed.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 20
0 <= X, Y <= 10 ^ 5
Where ‘T’ denotes the number of test cases
Time Limit: 1 sec.
2
8 4
3 10
4
3
In test case 1:
In the first operation, we convert 8 to 7 ( 8 - 1 = 7 )
In the second operation, we convert 7 to 6 ( 7 - 1 = 6 )
In the third operation, we convert 6 to 5 ( 6 - 1 = 5 )
In the fourth operation, we convert 5 to 4 ( 5 - 1 = 4 )
Thus a minimum of 4 operations is required for conversion.
In test case 2:
In the first operation, we convert 3 to 6 ( 3*2 = 6 )
In the second operation, we convert 6 to 5 ( 6 - 1 = 5 )
In the third operation, we convert 5 to 10 ( 5*2 = 10 )
Thus a minimum of 3 operations is required for conversion.
3
6 17
19 25
12 19
5
8
4
We can check every possibility but constraints are high can we store the previously occurred subproblem?
Explanation:
Algorithm:
Note: ‘INF’ represents INFINITY which is a large value that cannot possible by the answer.
O(Y), where ‘Y’ is given in the problem.
In the worst case, the recursion will work for all values of ‘X’ <= ‘Y’, thus O(Y).
O(Y), where ‘Y’ is given in the problem.
We are creating a DP of size ‘Y’+1 thus space complexity is O(Y)