Given an integer array A consisting of N integers. In a single transfer, we will be able to make a selection any index i ( 0 ⤠i ⤠N-1) and divide it both through 2 or 3(the quantity A[i] will have to be divisible through 2 or 3, respectively), the duty is to search out the minimal quantity of overall strikes required such that each one array parts are equivalent. If it isn’t imaginable to make all parts equivalent, print -1.
Examples:
Enter: N = 3, A[] = [1, 4, 3]
Output: 3
Rationalization: Divide A[1] through 2 two times and A[2] through 3 as soon as. Therefore at least 3 strikes are required.Enter: N = 3, A[] = [2, 7, 6]
Output: -1
Rationalization: It’s not imaginable to make all array parts equivalent.
Way: To resolve the issue apply the underneath concept:
First, letâs factorize every A[i] within the type of 3p*2q*z. Now it’s simple to look that if for any i, j if the values zi and zj aren’t equivalent, then it’s unimaginable to make all of the array parts equivalent. On this case, go back -1 as the solution. Differently, we will be able to calculate the sum of all p and q over all parts and print that as the solution.
Steps that had been to apply the above manner:Â
- Allow us to to find the gcd g of the entire array and divide all numbers through g so that we have got all of the different elements as opposed to 2 or 3 separated.
- Initialize a variable ans = 0 which is able to retailer the overall collection of strikes required to make all parts equivalent.Â
- For every A[i], divide it through 2 until A[i] is divisible through 2 and increment ans = ans + 1.
- Now, repeat the above procedure, however this time divide it through 3.
- Print the general solution as ans.
Beneath is the code to put into effect the above manner:
C++
|
Time Complexity: O(N*max(logA[i]))
Auxiliary Area: O(1)