![]() |
VOOZH | about |
Given an array of size n, the task is to find the minimum number of operations required in the array such that the product of all array elements is divisible by nth power of 2. In one operation, you can select any index i and multiply ai by i, you can perform an operation on a particular index at most 1 time. (Follow 1-based indexing)
Examples:
Input: arr[] = { 10, 6, 11 }
Output: 1
Explanation: We can apply operation at index 2.
Input: arr[] = {13, 17, 1, 1 }
Output: -1
Explanation: We can not make the product such that divisible by 2n
Approach: To solve the problem follow the below idea:
We will apply operation till the product of the array is not divisible by 2n and apply operation on that index first which give us maximum 2s.
Illustration:
Lets take an example : arr[] = { 6, 1, 5, 1 }
- The product of the array is 30 which is not divisible by 24 here n=4
- We will apply an operation on index 4 because index 4 gives us maximum 2s than index 1, 2, 3. Then the product of the array becomes 120 which is not divisible by 24
- Then, we will apply an operation on index 2, because index 4 is already operated and index 2 gives a maximum 2 than index 1 and 3.
- Then, the product of the array becomes 240 which is divisible by 24.
- In total, it requires 2 operations to make the product of the array such that it is divisible by 2n.
Below are the steps for the above approach:
Below is the code for the above approach:
1
Time Complexity: O(n*log2n)
Auxiliary Space: O(n)