Finding ' k ' such that its modulus with each array element is same | C ++ implementation of finding all k such that arr [ i ] % k is same for each i ; Prints all k such that arr [ i ] % k is same for all i ; sort the numbers ; max difference will be the difference between first and last element of sorted array ; Case when all the array elements are same ; Find all divisors of d and store in a vector v [ ] ; check for each v [ i ] if its modulus with each array element is same or not ; checking for each array element if its modulus with k is equal to k or not ; if check is true print v [ i ] ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printEqualModNumbers ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int d = arr [ n - 1 ] - arr [ 0 ] ; if ( d == 0 ) { cout << " Infinite ▁ solution " ; return ; } vector < int > v ; for ( int i = 1 ; i * i <= d ; i ++ ) { if ( d % i == 0 ) { v . push_back ( i ) ; if ( i != d / i ) v . push_back ( d / i ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int temp = arr [ 0 ] % v [ i ] ; int j ; for ( j = 1 ; j < n ; j ++ ) if ( arr [ j ] % v [ i ] != temp ) break ; if ( j == n ) cout << v [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 38 , 6 , 34 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printEqualModNumbers ( arr , n ) ; return 0 ; }