No of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | C # 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
using System ; class GFG { static int countPairs ( int [ ] a , int n , int x , int k ) { Array . Sort ( a ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int d = ( a [ i ] - 1 ) / x ; int a1 = Math . Max ( ( d + k ) * x , a [ i ] ) ; int it1 = Array . BinarySearch ( a , a1 ) ; int a2 = Math . Max ( ( d + k + 1 ) * x , a [ i ] ) ; int it2 = Array . BinarySearch ( a , a2 ) ; ans += Math . Abs ( it2 - it1 ) ; } return ans ; } static void Main ( ) { int [ ] a = { 1 , 3 , 5 , 7 } ; int n = a . Length ; int x = 2 , k = 1 ; Console . Write ( countPairs ( a , n , x , k ) ) ; } }