Suppose we have a list of numbers called nums, with unique positive numbers nums. We have to find the number of quadruples like (a, b, c, d) from nums such that a*b = c*d, a, b, c and d all are distinct elements of nums.
So, if the input is like nums = [3, 6, 4, 8], then the output will be 8, because the quadruples are [[3,8,6,4], [3,8,4,6], [8,3,6,4], [8,3,4,6], [6,4,3,8], [4,6,3,8], [6,4,8,3], [4,6,8,3]].
To solve this, we will follow these steps −
- c := a new map
- n := size of nums
- for i in range 0 to n - 1, do
- for j in range i + 1 to n - 1, do
- x := nums[i] * nums[j]
- c[x] := 1 + (c[x] if available, otherwise 0)
- for j in range i + 1 to n - 1, do
- ret := 0
- for each x in list of all values in c, do
- ret := ret + x *(x - 1)
- return ret * 4
Example
Let us see the following implementation to get better understanding −
def solve(nums): c = {} n = len(nums) for i in range(n): for j in range(i + 1, n): x = nums[i] * nums[j] c[x] = c.get(x, 0) + 1 ret = 0 for x in c.values(): ret += x * (x - 1) return ret * 4 nums = [3, 6, 4, 8] print(solve(nums))
Input
[3, 6, 4, 8]
Output
8