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 an array Arr[] of integers with length n and a number M. The array is only containing positive integers. The goal is to count the triplets of elements of Arr[] which have product equal to M.
We will do this by using three for loops. Increment count if arr[x]*arr[y]*arr[z]=M and x!=y!=z. (0<= x,y,z
Let’s understand with examples.
Input
arr[]= { 1,2,3,0,2,4 }, M=24
Output
Number of triplets with product M: 2
Explanation
Triplets with arr[x]*arr[y]*arr[z]==M.
Arr{}=[ 1,2,3,0,2,4 ] =(2,3,4) → 2*3*4=24
Arr{}=[ 1,2,3,0,2,4 ] =(3,2,4) → 3*2*4=24
Total triplets: 2
Input
arr[]= {2,2,2,2,2}, M=6
Output
Number of triplets with product M: 0
Explanation
Every triplet has product equal to 8 Total triplets: 0
Approach used in the below program is as follows
We take an integer array Arr[] initialized with random numbers.
Variable N stores the length of Arr[].
Function productisM(int arr[],int n,int m) takes an array, its length returns the triplets in which product is equal to m.
Take the initial variable count as 0 for the number of triplets.
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.
Check if arr[i]*arr[j]*arr[k]==m . If true 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 result.
Example
#include <bits/stdc++.h>
using namespace std;
int productisM(int arr[], int n, int m){
int count = 0;
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++){
int prod=arr[i]*arr[j]*arr[k];
if(prod==m)
{ count++; }
}
}
}
return count;
}
int main(){
int Arr[]={ 1,2,3,0,2,4 };
int N=6; //length of array
int M=24;
cout <<endl<< "Number of triplets with product M : "<<productisM(Arr,N,M);
return 0;
}
Output
If we run the above code it will generate the following output −
Number of triplets with product M: 4