Find all pairs ( a , b ) in an array such that a % b = k | Java 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 method
import java . util . HashMap ; import java . util . Vector ; class Test { static Vector < Integer > findDivisors ( int n ) { Vector < Integer > v = new Vector < > ( ) ; 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 ; } static boolean printPairs ( int arr [ ] , int n , int k ) { HashMap < Integer , Boolean > occ = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) occ . put ( arr [ i ] , true ) ; boolean isPairFound = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( occ . get ( k ) && k < arr [ i ] ) { System . out . print ( " ( " + k + " , ▁ " + arr [ i ] + " ) ▁ " ) ; isPairFound = true ; } if ( arr [ i ] >= k ) { Vector < Integer > v = findDivisors ( arr [ i ] - k ) ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( arr [ i ] % v . get ( j ) == k && arr [ i ] != v . get ( j ) && occ . get ( v . get ( j ) ) ) { System . out . print ( " ( " + arr [ i ] + " , ▁ " + v . get ( j ) + " ) ▁ " ) ; isPairFound = true ; } } v . clear ( ) ; } } return isPairFound ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 1 , 2 , 5 , 4 } ; int k = 2 ; if ( printPairs ( arr , arr . length , k ) == false ) System . out . println ( " No ▁ such ▁ pair ▁ exists " ) ; } }