

‘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.
For each test case, print the count of unique pairs having their product divisible by ‘K’.
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
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)
A number with a factor ‘x’ will form a pair with a number with a factor ‘y’ if ‘x * y’ is divisible by ‘K’.
It can be shown that if ‘nums[i] * nums[j] % K == 0’, then ‘gcd(nums[i], K) * gcd(nums[j], K) % K == 0’.
Proof:
Here GCD/gcd means the Greatest Common Divisor of the two numbers.
So The whole idea is to break down (factorize) the numbers and multiply them with the required factors so that their overall product is divisible by K.
We can do this using Hash Map.
So firstly, we will iterate on the given array and insert all the ‘gcd(nums[i], K)’ in the map.
Then we will iterate on the map and find all the pairs having ‘gcd(nums[i], K) * gcd(nums[j],K) % K == 0’. As the max number of factors for a given K <= 10^6, is 240, our solution will fit in the time limit.
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 and return the count of pairs whose product is divisible by ‘K’.
Int pairProductDivByK(n, k, nums)