Find all pairs ( a , b ) in an array such that a % b = k | C # program to find all pairs such that a % b = k . ; Utility method to find the divisors of n and store in vector v [ ] ; Vector is used to store the divisors ; If n is a square number , push only one occurrence ; method to find pairs such that ( a % b = k ) ; Store all the elements in the map to use map as hash for finding elements in O ( 1 ) time . ; Print all the pairs with ( a , b ) as ( k , numbers greater than k ) as k % ( num ( > k ) ) = k i . e . 2 % 4 = 2 ; Now check for the current element as ' a ' how many b exists such that a % b = k ; find all the divisors of ( arr [ i ] - k ) ; Check for each divisor i . e . arr [ i ] % b = k or not , if yes then print that pair . ; Clear vector ; Driver Code
using System ; using System . Collections . Generic ; class GFG { public static List < int > findDivisors ( int n ) { List < int > v = new List < int > ( ) ; for ( int i = 1 ; i <= Math . Sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { v . Add ( i ) ; } else { v . Add ( i ) ; v . Add ( n / i ) ; } } } return v ; } public static bool printPairs ( int [ ] arr , int n , int k ) { Dictionary < int , bool > occ = new Dictionary < int , bool > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { occ [ arr [ i ] ] = true ; } bool isPairFound = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( occ [ k ] && k < arr [ i ] ) { Console . Write ( " ( " + k + " , ▁ " + arr [ i ] + " ) ▁ " ) ; isPairFound = true ; } if ( arr [ i ] >= k ) { List < int > v = findDivisors ( arr [ i ] - k ) ; for ( int j = 0 ; j < v . Count ; j ++ ) { if ( arr [ i ] % v [ j ] == k && arr [ i ] != v [ j ] && occ [ v [ j ] ] ) { Console . Write ( " ( " + arr [ i ] + " , ▁ " + v [ j ] + " ) ▁ " ) ; isPairFound = true ; } } v . Clear ( ) ; } } return isPairFound ; } public static void Main ( string [ ] args ) { int [ ] arr = new int [ ] { 3 , 1 , 2 , 5 , 4 } ; int k = 2 ; if ( printPairs ( arr , arr . Length , k ) == false ) { Console . WriteLine ( " No ▁ such ▁ pair ▁ exists " ) ; } } }