Find all pairs ( a , b ) in an array 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 method
function findDivisors ( n ) { let v = [ ] ; for ( let i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) v . push ( i ) ; else { v . push ( i ) ; v . push ( Math . floor ( n / i ) ) ; } } } return v ; } function printPairs ( arr , n , k ) { let occ = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) occ . set ( arr [ i ] , true ) ; let isPairFound = false ; for ( let i = 0 ; i < n ; i ++ ) { if ( occ . get ( k ) && k < arr [ i ] ) { document . write ( " " + k + " " + arr [ i ] + " " ) ; isPairFound = true ; } if ( arr [ i ] >= k ) { let v = findDivisors ( arr [ i ] - k ) ; for ( let j = 0 ; j < v . length ; j ++ ) { if ( arr [ i ] % v [ j ] == k && arr [ i ] != v [ j ] && occ . get ( v [ j ] ) ) { document . write ( " " + arr [ i ] + " " + v [ j ] + " " ) ; isPairFound = true ; } } v = [ ] ; } } return isPairFound ; } let arr = [ 3 , 1 , 2 , 5 , 4 ] ; let k = 2 ; if ( printPairs ( arr , arr . length , k ) == false ) document . write ( " " ) ;