- 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

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.

#include<bits/stdc++.h> using namespace std; int equal_modulus (int arr[], int len) { sort(arr, arr + len); int diff = arr[len-1] - arr[0]; //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[0]%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[0]); cout << "The values of K :" << endl; equal_modulus(arr, len); return 0; }

The values of K : 1 2 10 5

- Related Questions & Answers
- Finding ‘k’ such that its modulus with each array element is same in C++
- Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ in C++
- C++ program to find unique pairs such that each element is less than or equal to N
- C# program to find K’th smallest element in a 2D array
- Find prime number K in an array such that (A[i] % K) is maximum in C++
- Find unique pairs such that each element is less than or equal to N in C++
- Python program to replace first ‘K’ elements by ‘N’
- Rearrange an array such that every odd indexed element is greater than its previous in C++
- Find minimum x such that (x % k) * (x / k) == n in C++
- Maximum value K such that array has at-least K elements that are >= K in C++
- K-th digit in ‘a’ raised to power ‘b’ in C++
- PHP program to find the first ‘n’ numbers that are missing in an array
- C++ Program to Find number of Ways to Partition a word such that each word is a Palindrome
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Write a program in C++ to count the Number of substrings that starts with ‘1’ and ends with ‘1’

Advertisements