- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Minimum operations to make XOR of array zero in C++
- Minimum removals from array to make GCD Greater in Python
- Minimum removals from array to make GCD Greater in C++
- Minimum delete operations to make all elements of array same in C++.
- Find minimum number of merge operations to make an array palindrome in C++
- Minimum number of operations on an array to make all elements 0 using C++.
- Find minimum operations needed to make an Array beautiful in C++
- Program to find minimum operations to make array equal using Python
- Minimum operations of given type to make all elements of a matrix equal in C++
- Minimum operations required to make all the array elements equal in C++
- Program to find minimum operations to make the array increasing using Python
- Program to find minimum number of operations to make string sorted in Python
- Make an array of multiple arrays in MongoDB?
- Minimum number of given operations required to make two strings equal using C++.
- Program to count minimum number of operations to flip columns to make target in Python

Advertisements