Count number of triplets with product equal to given number with duplicates allowed in C++


We are given with an array of numbers Arr[]. The goal is to count the number of triplets whose product is equal to the given number p. There can be more than one triplet with the same values but different elements. For example, (1,2,3) and (3,1,2) in array [1,2,3,1,2] will be counted as different if elements are different but values are the same.

Let’s understand with examples.

Input − arr[]= { 1,2,3,2,4,1,5 }, p=4

Output − Number of triplets: 3

Explanation

Triplet 1[ 1,2,3,2,4,1,5 ] → (1,2,2) product=4
Triplet 2 [ 1,2,3,2,4,1,5 ] → (1,4,1) product=4
Triplet 3 [ 1,2,3,2,4,1,5 ] → (2,2,1) product=4
Number of triplets with product 4 is 3.

Input − arr[]= { 1,1,2,1,2,2 }, p=8

Output − Number of triplets − 1

Explanation

Triplet 1 [ 1,1,2,1,2,2 ] → (2,2,2) product=8
Number of triplets with product 8 is 1

Approach used in the below program is as follows

  • We take an integer array Arr[] initialized with random numbers.

  • Take a variable product which stores the Product value. N stores the length of Arr[].

  • Function countTriplets(int arr[],int n,int p) takes an array, its length and product as input and returns the triplets whose product is equal to p.

  • Take the initial variable count as 0 for the number of triplets.

  • Take the initial variable prod as the product of each triplet. Initially 1.

  • Traverse array using three for loops for each element of the triplet.

  • Outermost loop from 0<=i<n-2, inner loop i<j<n-1, innermost j<k<n.

  • Calculate prod=arr[i]*arr[j]*arr[k]. If prod==p then increment count.

  • At the end of all loops count will have a total number of triplets that meet the condition.

  • Return the count as desired result.

Example

#include <bits/stdc++.h>
using namespace std;
int countTriplets(int arr[],int n,int p){
   int count = 0;
   int prod=1;
   for (int i = 0; i < n-2; i++){
      for (int j = i+1; j < n-1; j++){
         for (int k = j+1; k < n; k++){
            prod=arr[i]*arr[j]*arr[k];
               if ( prod==p ){
                  count++;
                  // cout<<endl<<"a :"<<arr[i]<<" b :"<<arr[j]<<" c :"<<arr[k]; //to print
               }
            }
         }
      }  
   }
   return count;
}
int main(){
   int Arr[]={ 1,2,3,6,1,6,3,2,1};
   int N=9; //length of array
   int product=6;
   cout <<endl<< "Number of triplets : "<<countTriplets(Arr,N,product);
   return 0;
}

Output

If we run the above code it will generate the following output −

Number of triplets : 18.

Updated on: 29-Aug-2020

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements