Given a integer array nums of length ‘N’ and an integer ‘K’, return the number of pairs ‘(i, j)’ such that:
1 <= ‘i’ < ‘j’ <= ‘N’ and ‘nums[i] * nums[j]’ is divisible by ‘K’.
EXAMPLE :‘N’ = 5, ‘K’ = 4, ‘nums’ = [2, 6, 1, 7, 8]
Output: 5
Explanation: (1, 2), (1, 5), (2, 5), (3, 5), and (4, 5) pairs have their products divisible by K.
The first line will contain the integer 'T', the number of test cases.
Each test case consists of two lines.
The first input line contains two integers, 'N' and 'K', separated by spaces.
Followed by a line containing space-separated ‘N’ positive integers, denoting the array nums.
Output format :
For each test case, print the count of unique pairs having their product divisible by ‘K’.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= 'T' <= 10
1 <= 'N' <= 10^5
1 <= 'K' <= 10^5
1 <= ‘nums[i]’ <= 10^6
It is guaranteed that sum of ‘N’ over all test cases is <= 10^5
Time Limit: 1 sec
2
4 5
1 2 3 4
5 2
1 2 3 4 5
0
7
For the first test case, there is no pair of indices whose corresponding product is divisible by 5.
For the second test case, the seven pairs of indices whose corresponding products are divisible by two are
(1, 2), (1, 4), (2, 3), (2, 4), (2, 5), (3, 4), and (4, 5).
Their products are 2, 4, 6, 8, 10, 12, and 20 respectively.
Other pairs such as (1, 3) and (3, 5) have products 3 and 15, respectively, which are not divisible by 2.
2
7 3
3 2 6 1 8 4 1
9 6
8 10 2 5 9 6 3 8 2
11
18
Check for every possible pair.
The idea is to iterate over all possible pairs and check if their product is divisible by ‘K’ or not.
If it is divisible by ‘K’ we will increment our answer count by one. Initially, its value will be zero.
Here the number of pairs can exceed the 32-bit integer type; hence we will use the 64-bit integer type to store the answer.
Algorithm:
// This function will iterate through every possible pair which can be formed using a given array ‘nums’ of length ‘N’ and return the count of pairs whose product is divisible by ‘K’.
Int pairProductDivByK(N, K, nums)
O(N * N), Where ‘N’ is the input integer denoting the size of the array ‘nums’.
As we are iterating through every possible pair of the array, It will take ‘(N * (N - 1))/2’ iterations which are of the order of O(N * N)
O(1)
We are using only the variable ‘ans’ to store the count of pairs having their product divisible by ‘K’ and loop variables. Hence, Space complexity is O(1), i.e., constant.