Print k numbers where all pairs are divisible by m | CPP program to find a list of k elements from an array such that difference between all of them is divisible by m . ; function to generate k numbers whose difference is divisible by m ; Using an adjacency list like representation to store numbers that lead to same remainder . ; stores the modulus when divided by m ; If we found k elements which have same remainder . ; If we could not find k elements ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print_result ( int a [ ] , int n , int k , int m ) { vector < int > v [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { int rem = a [ i ] % m ; v [ rem ] . push_back ( a [ i ] ) ; if ( v [ rem ] . size ( ) == k ) { for ( int j = 0 ; j < k ; j ++ ) cout << v [ rem ] [ j ] << " ▁ " ; return ; } } cout << " - 1" ; } int main ( ) { int a [ ] = { 1 , 8 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; print_result ( a , n , 2 , 3 ) ; return 0 ; }