Minimum operations to make GCD of array a multiple of k in C++

C++Server Side ProgrammingProgramming

Suppose we have an array arr and another value k. We have to find a minimum number of operations to make the GCD of the array equal to the multiple of k. In this case, the operation is increasing or decreasing the value. Suppose the array is like {4, 5, 6}, and k is 5. We can increase 4 by 1, and decrease 6 by 1, so it becomes 5. Here a number of operations is 2.

We have to follow these steps to get the result −

Steps

  • for all elements e in the array, follow steps 2 and 3
  • if e is not 1, and e > k, then increase result as min of (e mod k) and (k – e mod k).
  • otherwise, result will be result + k – e
  • return result

Example

 Live Demo

#include <iostream>
using namespace std;
int countMinOp(int arr[], int n, int k) {
   int result = 0;
   for (int i = 0; i < n; ++i) {
      if (arr[i] != 1 && arr[i] > k) {
         result = result + min(arr[i] % k, k - arr[i] % k);
      } else {
         result = result + k - arr[i];
      }
   }
   return result;
}
int main() {
   int arr[] = { 4, 5, 6 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 5;
   cout << "Minimum operation required: " << countMinOp(arr, n, k);
}

Output

Minimum operation required: 2
raja
Published on 21-Oct-2019 07:32:11
Advertisements