No of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | Java program to calculate the number pairs satisfying th condition ; function to calculate the number of pairs ; traverse through all elements ; current number 's divisor ; use binary search to find the element after k multiples of x ; use binary search to find the element after k + 1 multiples of x so that we get the answer bu subtracting ; the difference of index will be the answer ; Driver code ; function call to get the number of pairs
import java . util . * ; class GFG { static int countPairs ( int a [ ] , int n , int x , int k ) { Arrays . sort ( a ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int d = ( a [ i ] - 1 ) / x ; int it1 = Arrays . binarySearch ( a , Math . max ( ( d + k ) * x , a [ i ] ) ) ; int it2 = Arrays . binarySearch ( a , Math . max ( ( d + k + 1 ) * x , a [ i ] ) ) ; ans += it1 - it2 ; } return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 3 , 5 , 7 } ; int n = a . length ; int x = 2 , k = 1 ; System . out . println ( countPairs ( a , n , x , k ) ) ; } }