# C++ program to find ‘k’ such that its modulus with each array element is same

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find an integer ‘k’, such that its modulus with each element of a given array is the same.

For example, let us suppose we have been given with an array,

arr = {12, 22, 32}

Then we have the output value of k = 1, 2, 5, 10.

Take the case of two values in the array ‘x’ and ‘y’ (x>y). Then we have (y+difference)%k = y%k. Solving this we get,

difference%k = 0

So, we will find all the divisors to the difference of the maximum and minimum element in the array and then check for each divisor if the remainder is same or not for every element in the array.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
int equal_modulus (int arr[], int len) {
sort(arr, arr + len);
int diff = arr[len-1] - arr;
//vector to store all the divisors
vector <int> divi;
for (int i = 1; i*i <= diff; i++) {
if (diff%i == 0) {
divi.push_back(i);
if (i != diff/i)
divi.push_back(diff/i);
}
}
//to check if remainder is equal for every element
for (int i = 0; i < divi.size(); i++) {
int temp = arr%divi[i];
int j;
for (j = 1; j < len; j++)
if (arr[j] % divi[i] != temp)
break;
//to print the values of k
if (j == len)
cout << divi[i] <<" ";
}
return 0;
}
int main() {
int arr[] = {12, 22, 32};
int len = sizeof(arr)/sizeof(arr);
cout << "The values of K :" << endl;
equal_modulus(arr, len);
return 0;
}

## Output

The values of K :
1 2 10 5