Mr. Modulo comes up with another problem related to modulo and this time he is interested in finding all the possible pairs a and b in the array arr[] such that a % b = k where k is a given integer. The array given will have distinct elements.
You are required to print how many such pairs exist.
Example 1:
Input:
N=5, K=3
arr[] = {2, 3, 5, 4, 7}
Output: 4
Explanation:
The pairs are -: 
7 % 4 = 3
3 % 4 = 3
3 % 5 = 3
3 % 7 = 3
 
Example 2:
Input:
N=2, K=3
arr[] = {1, 2} 
Output: 0
 
Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function printPairs() that takes array arr, integer n and integer k as parameters and return the total number of such pairs in the array.
 
Expected Time Complexity:  O(N* sqrt(max)) where max is the maximum element in the array.
Expected Auxiliary Space: O(N).
 
Constraints:
1 ≤ N ≤ 10^{4}

Source: geeksforgeeks | Difficulty: MEDIUM
Tags: Number theory

Data structures

Starter code: #User function Template for python3

class Solution:
    def printPairs(self,a,n,k):
        #code here.



Solutions:
class Solution:

	def divisors(self, val):
		ans = []
		for i in range(1, int(val ** 0.5) + 1):
			if val % i == 0:
				if val // i == i:
					ans.append(i)
				else:
					ans.append(i)
					ans.append(val // i)
		return ans

	def printPairs(self, a, n, h):
		a.sort()
		count = 0
		_set = set(a)
		k = h
		for i in range(n):
			val = a[i]
			if k in _set and val > k:
				count += 1
			if val >= k:
				arr = self.divisors(val - k)
				for j in arr:
					if j in _set and val % j == k and (val != j):
						count += 1
		return count


class Solution:

	def printPairs(self, arr, n, k):

		def find(N):
			res = []
			p = 1
			while p * p <= N:
				if N % p == 0:
					res.append(p)
					if N // p != p:
						res.append(N // p)
				p += 1
			return res
		ans = 0
		uset = set()
		for a in arr:
			uset.add(a)
		for i in range(n):
			if k in uset and k < arr[i]:
				ans += 1
			if arr[i] >= k:
				a = arr[i]
				divs = find(a - k)
				for b in divs:
					if b in uset and a % b == k and (a != b):
						ans += 1
		return ans


from math import sqrt

class Solution:

	def printPairs(self, a, n, k):

		def factors(n):
			divisors = []
			for i in range(1, int(sqrt(n)) + 1):
				if n % i == 0:
					if n // i == i:
						divisors.append(i)
					else:
						divisors.append(i)
						divisors.append(n // i)
			return divisors
		count = 0
		occ = dict()
		for i in a:
			occ[i] = True
		for i in range(n):
			if k in occ and k < a[i]:
				count += 1
			if a[i] >= k:
				div = factors(a[i] - k)
				for j in div:
					if a[i] % j == k and a[i] != j and (j in occ):
						count += 1
		return count