Count all possible pairs in given Array with product K
Last Updated :
07 Dec, 2023
Given an integer array arr[] of size N and a positive integer K, the task is to count all the pairs in the array with a product equal to K.
Examples:
Input: arr[] = {1, 2, 16, 4, 4, 4, 8 }, K=16
Output: 5
Explanation: Possible pairs are (1, 16), (2, 8), (4, 4), (4, 4), (4, 4)
Input: arr[] = {1, 10, 20, 10, 4, 5, 5, 2 }, K=20
Output: 5
Explanation: Possible pairs are (1, 20), (2, 10), (2, 10), (4, 5), (4, 5)
Naive Approach:
The naive approach for the problem is to run two nested loops to generate each possible pair and then for each pair generated check their product value. If their product comes out to be same as K then increment the count.
Algorithm:
- Initialize a variable count as 0.
- Traverse the array from index i=0 to i=N-1.
- For each i, traverse the array from index j=i+1 to j=N-1.
- For each pair (i,j), check if their product is equal to K.
- If their product is equal to K, increment the count.
- After completing the loops, return the count.
Below is the implementation of the approach:
C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;
// Function to count pairs with product equal to K
int countPairsWithProductK(int arr[], int n, int k) {
int count = 0;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
int main() {
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 16;
// Function Call
int result = countPairsWithProductK(arr, n, k);
// Print the result
cout << result << endl;
return 0;
}
Java
import java.util.*;
public class Main {
// Function to count pairs with product equal to K
static int countPairsWithProductK(int[] arr, int k) {
int count = 0;
int n = arr.length;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
public static void main(String[] args) {
int[] arr = { 1, 2, 16, 4, 4, 4, 8 };
int k = 16;
// Function Call
int result = countPairsWithProductK(arr, k);
// Print the result
System.out.println(result);
}
}
Python3
# Function to count pairs with product equal to K
def countPairsWithProductK(arr, k):
count = 0
n = len(arr)
# Traverse through all possible pairs of the array
for i in range(n):
for j in range(i + 1, n):
# Check if the product of the current pair is equal to K
if arr[i] * arr[j] == k:
count += 1
# Return the count of pairs with product equal to K
return count
# Driver's code
arr = [1, 2, 16, 4, 4, 4, 8]
k = 16
# Function Call
result = countPairsWithProductK(arr, k)
# Print the result
print(result)
C#
using System;
class CountPairsWithProductK {
// Function to count pairs with product equal to K
static int CountPairs(int[] arr, int n, int k)
{
int count = 0;
// Traverse through all possible pairs of the array
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the product of the current pair
// is equal to K
if (arr[i] * arr[j] == k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver program to test CountPairs
static void Main()
{
int[] arr = { 1, 2, 16, 4, 4, 4, 8 };
int n = arr.Length;
int k = 16;
// Function Call
int result = CountPairs(arr, n, k);
// Print the result
Console.WriteLine(result);
}
}
JavaScript
// Function to count pairs with product equal to K
function countPairsWithProductK(arr, k) {
let count = 0;
const n = arr.length;
// Traverse through all possible pairs of the array
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Check if the product of the current pair is equal to K
if (arr[i] * arr[j] === k) {
count++;
}
}
}
// Return the count of pairs with product equal to K
return count;
}
// Driver's code
const arr = [1, 2, 16, 4, 4, 4, 8];
const k = 16;
// Function Call
const result = countPairsWithProductK(arr, k);
// Print the result
console.log(result);
Time Complexity: O(N*N) because two nested loops are executing. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.
Approach: The idea is to use hashing to store the elements and check if K/arr[i] exists in the array or not using the map and increase the count accordingly.
Follow the steps below to solve the problem:
- Initialize the variable count as 0 to store the answer.
- Initialize the unordered_map<int, int> mp[].
- Iterate over the range [0, N) using the variable i and store the frequencies of all elements of the array arr[] in the map mp[].
- Iterate over the range [0, N) using the variable i and perform the following tasks:
- Initialize the variable index as K/arr[i].
- If K is not a power of 2 and index is present in map mp[] then increase the value of count by mp[arr[i]]*mp[index] and erase both of them from the map mp[].
- If K is a power of 2 and index is present in map mp[] then increase the value of count by mp[index]*(mp[index]-1)/2 and erase it from the map mp[].
- After performing the above steps, print the value of count as the answer.
Below is the implementation of the above approach.
C++14
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count
// the total number of pairs
int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0;
// Initialize hashmap.
unordered_map<int, int> mp;
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
mp[arr[i]]++;
}
for (int i = 0; i < n; i++) {
double index = 1.0 * k / arr[i];
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
// After counting erase the element
mp.erase(arr[i]);
mp.erase(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.find(k / arr[i]) != mp.end()
&& (index == arr[i])) {
// Pair count
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
// After counting erase the element;
mp.erase(arr[i]);
}
}
return count;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 16;
cout << countPairsWithProductK(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count
// the total number of pairs
static int countPairsWithProductK(
int arr[], int n, int k)
{
int count = 0;
// Initialize hashmap.
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
if(mp.containsKey(arr[i])){
mp.put(arr[i], mp.get(arr[i])+1);
}else{
mp.put(arr[i], 1);
}
}
for (int i = 0; i < n; i++) {
int index = (int) (1.0 * k / arr[i]);
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.containsKey(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
// After counting erase the element
mp.remove(arr[i]);
mp.remove(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.containsKey(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1))
/ 2;
// After counting erase the element;
mp.remove(arr[i]);
}
}
return count;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 16, 4, 4, 4, 8 };
int N = arr.length;
int K = 16;
System.out.print(countPairsWithProductK(arr, N, K));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach
from collections import defaultdict
# Function to count
# the total number of pairs
def countPairsWithProductK(arr, n, k):
count = 0
# Initialize hashmap.
mp = defaultdict(int)
# Insert array elements to hashmap
for i in range(n):
mp[arr[i]] += 1
for i in range(n):
index = 1.0 * k / arr[i]
# If k is not power of two
if (index >= 0
and ((index - (int)(index)) == 0)
and (k / arr[i]) in mp
and (index != arr[i])):
count += mp[arr[i]] * mp[index]
# After counting erase the element
del mp[arr[i]]
del mp[index]
# If k is power of 2
if (index >= 0
and ((index - (int)(index)) == 0)
and (k / arr[i]) in mp
and (index == arr[i])):
# Pair count
count += ((mp[arr[i]]
* (mp[arr[i]] - 1)) / 2)
# After counting erase the element;
del mp[arr[i]]
return count
# Driver Code
if __name__ == "__main__":
arr = [1, 2, 16, 4, 4, 4, 8]
N = len(arr)
K = 16
print(int(countPairsWithProductK(arr, N, K)))
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to count
// the total number of pairs
static int countPairsWithProductK(
int []arr, int n, int k)
{
int count = 0;
// Initialize hashmap.
Dictionary<int,int> mp = new Dictionary<int,int>();
// Insert array elements to hashmap
for (int i = 0; i < n; i++) {
if(mp.ContainsKey(arr[i])){
mp[arr[i]] = mp[arr[i]]+1;
}else{
mp.Add(arr[i], 1);
}
}
for (int i = 0; i < n; i++) {
int index = (int) (1.0 * k / arr[i]);
// If k is not power of two
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index != arr[i])) {
count += mp[arr[i]] * mp[index];
// After counting erase the element
mp.Remove(arr[i]);
mp.Remove(index);
}
// If k is power of 2
if (index >= 0
&& ((index - (int)(index)) == 0)
&& mp.ContainsKey(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp[arr[i]]
* (mp[arr[i]] - 1))
/ 2;
// After counting erase the element;
mp.Remove(arr[i]);
}
}
return count;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 2, 16, 4, 4, 4, 8 };
int N = arr.Length;
int K = 16;
Console.Write(countPairsWithProductK(arr, N, K));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript code for the above approach
// Function to count
// the total number of pairs
function countPairsWithProductK(
arr, n, k) {
let count = 0;
// Initialize hashmap.
let mp = new Map();
// Insert array elements to hashmap
for (let i = 0; i < n; i++) {
if (mp.has(arr[i])) {
mp.set(arr[i], mp.get(arr[i]) + 1);
}
else {
mp.set(arr[i], 1);
}
}
for (let i = 0; i < n; i++) {
let index = 1.0 * k / arr[i];
// If k is not power of two
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index != arr[i])) {
count += mp.get(arr[i]) * mp.get(index);
// After counting erase the element
mp.delete(arr[i]);
mp.delete(index);
}
// If k is power of 2
if (index >= 0
&& ((index - Math.floor(index)) == 0)
&& mp.has(k / arr[i])
&& (index == arr[i])) {
// Pair count
count += (mp.get(arr[i])
* (mp.get(arr[i]) - 1))
/ 2;
// After counting erase the element;
mp.delete(arr[i]);
}
}
return count;
}
// Driver Code
let arr = [1, 2, 16, 4, 4, 4, 8];
let N = arr.length;
let K = 16;
document.write(countPairsWithProductK(arr, N, K));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Product of all the pairs from the given array Given an array arr[] of N integers, the task is to find the product of all the pairs possible from the given array such as: (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. Print the resultant answer modulus 10^9+7. Exam
11 min read
Count pairs in Array whose product is divisible by K Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j. Examples: Input: vec = {1, 2, 3, 4, 5, 6}, K = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
11 min read
Count pairs whose products exist in array Given an array, count those pair whose product value is present in array. Examples: Input : arr[] = {6, 2, 4, 12, 5, 3}Output : 3 All pairs whose product exist in array (6 , 2) (2, 3) (4, 3) Input : arr[] = {3, 5, 2, 4, 15, 8}Output : 2 A Simple solution is to generate all pairs of given array and c
15+ min read
Count pairs in Array whose product is a Kth power of any positive integer Given an array arr[] of length N and an integer K, the task is to count pairs in the array whose product is Kth power of a positive integer, i.e. A[i] * A[j] = ZK for any positive integer Z. Examples: Input: arr[] = {1, 3, 9, 8, 24, 1}, K = 3 Output: 5 Explanation: There are 5 such pairs, those can
14 min read
Count of index pairs in array whose range product is a positive integer Given an array A of non-zero integers, the task is to find the number of pairs (l, r) where (l <= r) such that A[l]*A[l+1]*A[l+2]....A[r] is positive. Examples: Input: A = {5, -3, 3, -1, 1} Output: 7 Explanation: First pair, (1, 1) = 5 is positive Second pair, (3, 3) = 3 is positive Third pair, (
6 min read