In this HackerEarth Bob And GCD problem solution Bob has an array A of size N. He doesn't like arrays in which the GCD of all elements is not K. He can perform multiple operations on an array. In each operation, he can either increase or decrease the value of an element by 1.
You have to tell the minimum operation Bob will take to make GCD of all elements in an array equal to K or any multiple of K?

Note: The smallest value up to which you can decrease any element is 1. You cannot make any element smaller than 1.

GCD here is Greatest Common Divisor.


HackerEarth Bob And GCD problem solution


HackerEarth Bob And GCD problem solution.

#include<bits/stdc++.h>
using namespace std;
long long min_operations (vector<int> A, int K) {
// Write your code here
long long ans=0;
for(int i=0;i<A.size();i++)
{
if(A[i]<K)
ans+=K-A[i];
else
ans+=min(A[i]%K,K-A[i]%K);
}
return ans;
}

int main() {

ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
for(int t_i=0; t_i<T; t_i++)
{
int K;
cin >> K;
int N;
cin >> N;
vector<int> A(N);
for(int i_A=0; i_A<N; i_A++)
{
cin >> A[i_A];
}


long long out_;
out_ = min_operations(A, K);

cout << out_;
cout << "\n";
}
}