Minimize divisions such that no Array element is divisible by K
Given an array arr[] of size N and an integer K, the task is to find the minimum operations such that no variable is divisible by K. In each operation:
- Select any integer X from the array.
- Divide all occurrences of X by K.
Examples:
Input: arr[] = [2, 3, 4, 5], K = 2
Output: 2
Explanation:
In the first operation, choose X = 4; Hence the resulting array will be [2, 3, 2, 5].
In the second operation, choose X = 2; Hence the resulting array will be [1, 3, 1, 5].
After these two operations, no X remained such that X % K = 0; hence, the answer is 2.Input: arr[] = [3, 5, 8, 12, 4], K = 4
Output: 3
Explanation:
First operation X = 12, arr[] = [3, 5, 8, 3, 4].
Second operation X = 8, arr[] = [3, 5, 2, 3, 4].
Third operation X = 4, arr[] = [3, 5, 2, 3, 1].
Approach: This problem can be solved with the help of greedy approach based on the following idea.
Select any element and repeatedly divide it by K until it is no more divisible. Do the same for all array elements and find the total count
Follow the steps mentioned below to solve the problem:
- Initialize an empty set to store all the different elements obtained while performing the operations.
- Loop over all elements of the array arr[].
- Run a while loop till current arr[i] is divisible by K.
- If arr[i] is not present in the set then insert it.
- Divide arr[i] by ‘K’.
- Run a while loop till current arr[i] is divisible by K.
- Return the size of the set as it represents the number of times division operation is performed.
Below is the implementation of the above approach :
C++
// C++ code to implement the approach #include <bits/stdc++.h>using namespace std; // Function to find// the minimum number of steps requiredint minimumOps(int n, int k, vector<int>& arr){ // Initializing an empty set 'elements'. set<int> elements; // Looping over the array 'arr'. for (int i = 0; i < n; i++) { // While loop till current // element is divisible by // 'k'. while (arr[i] % k == 0) { // If current array element is // not in the set then insert it. if (elements.find(arr[i]) == elements.end()) { elements.insert(arr[i]); } // Dividing the current // array element by 'k'. arr[i] /= k; } } // Returning the answer: // size of the set 'elements'. return (int)elements.size();} // Driver codeint main(){ int N = 5, K = 4; vector<int> arr = { 3, 5, 8, 12, 4 }; // Function call cout << minimumOps(n, k, arr); return 0;} |
3
Time Complexity: O(N * LogM), where M is the maximum element of the array.
Auxiliary Space: O(N)

