Count number of triplets with product equal to given number - GeeksforGeeks

08 Jun, 2021
Given an array of distinct integers(considering only positive numbers) and a number ‘m’, find the number of triplets with product equal to ‘m’.Examples:  
Input : arr[] = { 1, 4, 6, 2, 3, 8}  
            m = 24
Output : 3
{1, 4, 6} {1, 3, 8} {4, 2, 3}

Input : arr[] = { 0, 4, 6, 2, 3, 8}  
            m = 18
Output : 0
Asked in : Microsoft 
A Naive approach is to consider each and every triplet one by one and count if their product is equal to m.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count triplets with given// product m#include <iostream>using namespace std; // Function to count such tripletsint countTriplets(int arr[], int n, int m){    int count = 0;     // Consider all triplets and count if    // their product is equal to m    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++)                if (arr[i] * arr[j] * arr[k] == m)                    count++;     return count;} // Drivers codeint main(){    int arr[] = { 1, 4, 6, 2, 3, 8 };    int n = sizeof(arr) / sizeof(arr[0]);    int m = 24;     cout << countTriplets(arr, n, m);     return 0;}
// Java program to count triplets with given// product m class GFG {    // Method to count such triplets    static int countTriplets(int arr[], int n, int m)    {        int count = 0;         // Consider all triplets and count if        // their product is equal to m        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++)                    if (arr[i] * arr[j] * arr[k] == m)                        count++;         return count;    }     // Driver method    public static void main(String[] args)    {        int arr[] = { 1, 4, 6, 2, 3, 8 };        int m = 24;         System.out.println(countTriplets(arr, arr.length, m));    }}
# Python3 program to count# triplets with given product m # Method to count such tripletsdef countTriplets(arr, n, m):         count = 0     # Consider all triplets and count if    # their product is equal to m    for i in range (n - 2):        for j in range (i + 1, n - 1):            for k in range (j + 1, n):                if (arr[i] * arr[j] * arr[k] == m):                    count += 1    return count # Driver codeif __name__ == "__main__":       arr = [1, 4, 6, 2, 3, 8]    m = 24    print(countTriplets(arr,                        len(arr), m)) # This code is contributed by Chitranayal
// C# program to count triplets// with given product musing System; public class GFG {         // Method to count such triplets    static int countTriplets(int[] arr, int n, int m)    {        int count = 0;         // Consider all triplets and count if        // their product is equal to m        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++)                    if (arr[i] * arr[j] * arr[k] == m)                        count++;         return count;    }     // Driver method    public static void Main()    {        int[] arr = { 1, 4, 6, 2, 3, 8 };        int m = 24;         Console.WriteLine(countTriplets(arr, arr.Length, m));    }} // This code is contributed by Sam007
<?php// PHP program to count triplets// with given product m // Function to count such tripletsfunction countTriplets($arr, $n, $m){    $count = 0;     // Consider all triplets and count if    // their product is equal to m    for ( $i = 0; $i < $n - 2; $i++)        for ( $j = $i + 1; $j < $n - 1; $j++)            for ($k = $j + 1; $k < $n; $k++)                if ($arr[$i] * $arr[$j] * $arr[$k] == $m)                    $count++;     return $count;}     // Driver code    $arr = array(1, 4, 6, 2, 3, 8);    $n = sizeof($arr);    $m = 24;    echo countTriplets($arr, $n, $m); // This code is contributed by jit_t.?>
<script>// Javascript program to count triplets with given// product m         // Method to count such triplets    function countTriplets(arr,n,m)    {        let count = 0;          // Consider all triplets and count if        // their product is equal to m        for (let i = 0; i < n - 2; i++)            for (let j = i + 1; j < n - 1; j++)                for (let k = j + 1; k < n; k++)                    if (arr[i] * arr[j] * arr[k] == m)                        count++;          return count;    }         // Driver method    let arr = [ 1, 4, 6, 2, 3, 8];    let m = 24;    document.write(countTriplets(arr, arr.length, m));         // This code is contributed by avanitrachhadiya2155     </script>
Output:  
3
Time Complexity: O(n3)An Efficient Method is to use Hashing.  
Store all the elements in a hash_map with their index.Consider all pairs(i, j) and check the following: If (arr[i]*arr[j] !=0 && (m % arr[i]*arr[j]) == 0), If yes, then search for ( m / (arr[i]*arr[j]) in the map.Also check m / (arr[i]*arr[j]) is not equal to arr[i] and arr[j].Also, check that the current triplet is not counted previously by using the index stored in the map.If all the above conditions are satisfied, then increment the count.Return count.
Store all the elements in a hash_map with their index.
Consider all pairs(i, j) and check the following: If (arr[i]*arr[j] !=0 && (m % arr[i]*arr[j]) == 0), If yes, then search for ( m / (arr[i]*arr[j]) in the map.Also check m / (arr[i]*arr[j]) is not equal to arr[i] and arr[j].Also, check that the current triplet is not counted previously by using the index stored in the map.If all the above conditions are satisfied, then increment the count.
If (arr[i]*arr[j] !=0 && (m % arr[i]*arr[j]) == 0), If yes, then search for ( m / (arr[i]*arr[j]) in the map.
Also check m / (arr[i]*arr[j]) is not equal to arr[i] and arr[j].
Also, check that the current triplet is not counted previously by using the index stored in the map.
If all the above conditions are satisfied, then increment the count.
Return count.
C++
Java
Python3
C#
Javascript
// C++ program to count triplets with given// product m#include <bits/stdc++.h>using namespace std; // Function to count such tripletsint countTriplets(int arr[], int n, int m){    // Store all the elements in a set    unordered_map<int, int> occ;    for (int i = 0; i < n; i++)        occ[arr[i]] = i;     int count = 0;     // Consider all pairs and check for a    // third number so their product is equal to m    for (int i = 0; i < n - 1; i++) {        for (int j = i + 1; j < n; j++) {            // Check if current pair divides m or not            // If yes, then search for (m / arr[i]*arr[j])            if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) {                int check = m / (arr[i] * arr[j]);                auto it = occ.find(check);                 // Check if the third number is present                // in the map and it is not equal to any                // other two elements and also check if                // this triplet is not counted already                // using their indexes                if (check != arr[i] && check != arr[j]                    && it != occ.end() && it->second > i                    && it->second > j)                    count++;            }        }    }     // Return number of triplets    return count;} // Drivers codeint main(){    int arr[] = { 1, 4, 6, 2, 3, 8 };    int n = sizeof(arr) / sizeof(arr[0]);    int m = 24;     cout << countTriplets(arr, n, m);     return 0;}
// Java program to count triplets with given// product m import java.util.HashMap; class GFG {    // Method to count such triplets    static int countTriplets(int arr[], int n, int m)    {        // Store all the elements in a set        HashMap<Integer, Integer> occ = new HashMap<Integer, Integer>(n);        for (int i = 0; i < n; i++)            occ.put(arr[i], i);         int count = 0;         // Consider all pairs and check for a        // third number so their product is equal to m        for (int i = 0; i < n - 1; i++) {            for (int j = i + 1; j < n; j++) {                // Check if current pair divides m or not                // If yes, then search for (m / arr[i]*arr[j])                if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) {                    int check = m / (arr[i] * arr[j]);                     occ.containsKey(check);                     // Check if the third number is present                    // in the map and it is not equal to any                    // other two elements and also check if                    // this triplet is not counted already                    // using their indexes                    if (check != arr[i] && check != arr[j]                        && occ.containsKey(check) && occ.get(check) > i                        && occ.get(check) > j)                        count++;                }            }        }         // Return number of triplets        return count;    }     // Driver method    public static void main(String[] args)    {        int arr[] = { 1, 4, 6, 2, 3, 8 };        int m = 24;         System.out.println(countTriplets(arr, arr.length, m));    }}
# Python3 program for the above approach # Function to find the tripletdef countTriplets(li,product):    flag = 0    count = 0         # Consider all pairs and check    # for a third number so their    # product is equal to product    for i in range(len(li)):                 # Check if current pair        # divides product or not        # If yes, then search for        # (product / li[i]*li[j])        if li[i]!= 0 and product % li[i] == 0:                         for j in range(i+1, len(li)):                                # Check if the third number is present                # in the map and it is not equal to any                # other two elements and also check if                # this triplet is not counted already                # using their indexes                if li[j]!= 0 and product % (li[j]*li[i]) == 0:                    if product // (li[j]*li[i]) in li:                                             n = li.index(product//(li[j]*li[i]))                                             if n > i and n > j:                            flag = 1                            count+=1    print(count)    # Driver codeli = [  1, 4, 6, 2, 3, 8 ]product = 24 # Function callcountTriplets(li,product)
// C# implementation of the above// approachusing System;using System.Collections.Generic;class GFG{     // Method to count such tripletsstatic int countTriplets(int[] arr,                         int n, int m){  // Store all the elements  // in a set  Dictionary<int,             int> occ = new Dictionary<int,                                       int>(n);    for (int i = 0; i < n; i++)    occ.Add(arr[i], i);   int count = 0;   // Consider all pairs and  // check for a third number  // so their product is equal to m  for (int i = 0; i < n - 1; i++)  {    for (int j = i + 1; j < n; j++)    {      // Check if current pair divides      // m or not If yes, then search      // for (m / arr[i]*arr[j])      if ((arr[i] * arr[j] <= m) &&          (arr[i] * arr[j] != 0) &&          (m % (arr[i] * arr[j]) == 0))      {        int check = m / (arr[i] * arr[j]);         //occ.containsKey(check);        // Check if the third number        // is present in the map and        // it is not equal to any        // other two elements and also        // check if this triplet is not        // counted already using their indexes        if (check != arr[i] &&            check != arr[j] &&            occ.ContainsKey(check) &&            occ[check] > i &&            occ[check] > j)          count++;      }    }  }   // Return number of triplets  return count;} // Driver codestatic void Main(){  int[] arr = {1, 4, 6,               2, 3, 8};  int m = 24;  Console.WriteLine(countTriplets(arr,                                  arr.Length, m));}} // This code is contributed by divyeshrabadiya07
<script> // Javascript program to count triplets with given// product m // Function to count such tripletsfunction countTriplets(arr, n, m){     // Store all the elements in a set    var occ = new Map();    for (var i = 0; i < n; i++)    {        occ.set(arr[i], i)    }     var count = 0;     // Consider all pairs and check for a    // third number so their product is equal to m    for (var i = 0; i < n - 1; i++)    {        for (var j = i + 1; j < n; j++)        {                     // Check if current pair divides m or not            // If yes, then search for (m / arr[i]*arr[j])            if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) {                var check = parseInt(m / (arr[i] * arr[j]));                 var ff = occ.has(check);                var ans;                if(ff)                    ans = occ.get(check)                 // Check if the third number is present                // in the map and it is not equal to any                // other two elements and also check if                // this triplet is not counted already                // using their indexes                if (check != arr[i] && check != arr[j]                    && ff && ans > i                    && ans > j)                    count++;            }        }    }     // Return number of triplets    return count;} // Drivers codevar arr = [1, 4, 6, 2, 3, 8];var n = arr.length;var m = 24;document.write( countTriplets(arr, n, m)); // This code is contributed by importantly.</script>
Output:  
3
Time Complexity : O(n2) Auxiliary Space : O(n)This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
swathypanayoor
ukasp
divyeshrabadiya07
avanitrachhadiya2155
importantly
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Multidimensional Arrays in Java
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Most frequent element in an array