You are given a positive integer 'N’. Your task is to find and return the minimum number of steps that 'N' has to take to get reduced to 1.
You can perform any one of the following 3 steps:
1) Subtract 1 from it. (n = n - 1) ,
2) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) ,
3) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ).
For example:
Given:
‘N’ = 4, it will take 2 steps to reduce it to 1, i.e., first divide it by 2 giving 2 and then subtract 1, giving 1.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The following ‘T’ lines contain a single integer ‘N’, denoting the number given to us.
Output Format :
For each test case, You are supposed to return an integer that denotes the minimum steps it takes to reduce the number to 1.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 5
1 <= ‘N’ <= 10 ^ 5
Time Limit: 1sec.
2
4
10
2
3
In the first test case, it will take 2 steps to reduce it to 1, i.e., first divide it by 2, giving 2, and then subtract 1, giving 1.
In the second test case, it will take 3 steps to reduce it to 1, i.e. first subtract 1, then divide by 3, two times. Therefore a total of 3 steps are required.
2
6
12
2
3
Can we use recursion for all possible cases?
The idea is to use recursion to find all possible cases and then, out of them, choose the minimum.
The steps are as follows:
O((3 ^ N)), Where ‘N’ is the number given to us.
Since we are using recursion and for each case, we have three calls, therefore the overall time complexity will be O(3 ^ N).
O(N), Where ‘N’ is the number given to us.
Since we are using recursion, a call stack up to height ‘N’ would be made. Hence the overall space complexity will be O(N).