
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Minimum operations to make XOR of array zero in C++
- 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++
- Find minimum operations needed to make an Array beautiful in C++
- Minimum removals from array to make GCD Greater in Python
- Minimum operations required to make all the array elements equal in C++
- Minimum number of operations on an array to make all elements 0 using C++.
- Minimum operations of given type to make all elements of a matrix equal in C++
- Program to find minimum operations to make array equal using Python
- Minimum operations required to remove an array in C++
- Program to find minimum operations to make the array increasing using Python
- Minimum number of given operations required to make two strings equal using C++.
- Minimum operations to make the MEX of the given set equal to x in C++
- Minimum move to end operations to make all strings equal in C++

Advertisements