Tuple with the same Product in C++

C++Server Side ProgrammingProgramming

Let us suppose we have an array of integers that contains distinct elements. The task is to count the total number of tuples such that they are all having the same product.

If the tuple is (a,b,c,d), then it would be valid if this tuple follows (a*b = c*d). For example,

Input-1:

arr[]= {2,4,6,3}

Output:

8

Explanation: Total number of Tuples are 8 and these are, (2 6 3 4),(2,6,4,3),(6,2,3,4),(6,2,4,3),(3,4,2,6),(4,3,2,6) ,(3,4,6,2), (4,3,6,2) in which a*b = c*d.

Approach to solve this problem −

The idea is to solve this problem is that we will use a hashmap for all the multiplication in pairs.

This will help to ensure that all the pairs stored in the map have the same multiplication.

After creating the map of multiplication of every element in the given array, we will traverse through the map will check, how many pairs are there which are having the same multiplication in the form of (a*b = c*d).

Since the total number of pairs can be counted as n*(n-1)/2 and in one pair there are ‘4’ numbers which can have at max 4*2 such permutations in that. Thus for every element, it can have, n*(n1)/2*8 pairs in that.

  • Take input of array elements.

  • An integer function countTuples(int *arr, int n) takes the array element and its size as the input. And returns the number of tuples having the same product in the form of (a*b = c*d).

  • Creating a hashmap such that key is the product of the pair and value as the frequency of those pairs.

  • Iterating over the map and counting the number of such tuples having the same product.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTuple(int *arr, int n) {
   map<int, int> mp;
   for (int i = 0; i < n; i++)
      for (int j = i + 1; j < n; j++)
         mp[arr[i] * arr[j]]++;
   int ans = 0;
   for (auto it : mp)
      ans += (it.second * (it.second - 1) / 2) * 8;
   return ans;
}
int main(){
   int n=4;
   int arr[n]= {2,4,6,3};
   int res= countTuple(arr,n);
   cout<<res<<" ";
   return 0;
}

Output

8

All the tuples having the same product tuples are 8.

raja
Published on 05-Feb-2021 10:44:09
Advertisements