
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Number of Triplets with Product Equal to Given Number 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.