Product of elements in an array having composite frequency

By | September 25, 2023

Given an array arr, the task is to find the product of the elements which have composite frequencies in the array.

Examples:

Input: arr[] = {4, 6, 5, 4, 6} 
Output: 5 
Only 5 occurs composite number time, So, 5 

Input: arr[] = {1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 3, 1} 
Output: 1 
Only 1 appears composite number of times i.e. 4 . So, 1

Approach:
Traverse the array and store the frequencies of all the elements in a map.
Build Sieve of Eratosthenes which will be used to test the primality of a number in O(1) time.
Calculate the product of elements having composite frequency using the Sieve array calculated in the previous step.

Below is the implementation of the above approach:

// C++ program to find product of elements
// in an array having composite frequency
#include <bits/stdc++.h>
using namespace std;

// Function to create Sieve to check primes
void SieveOfEratosthenes(bool prime[], int p_size)
{
    // False here indicates
    // that it is not prime
    prime[0] = false;
    prime[1] = false;

    for (int p = 2; p * p <= p_size; p++) {

        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p]) {

            // Update all multiples of p,
            // set them to non-prime
            for (int i = p * 2; i <= p_size; i += p)
                prime[i] = false;
        }
    }
}

// Function to return the product of elements
// in an array having composite frequency
int productOfElements(int arr[], int n)
{
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));

    SieveOfEratosthenes(prime, n + 1);

    int i, j;

    // Map is used to store
    // element frequencies
    unordered_map<int, int> m;
    for (i = 0; i < n; i++)
        m[arr[i]]++;

    int product = 1;

    // Traverse the map using iterators
    for (auto it = m.begin(); it != m.end(); it++) {

        // Count the number of elements
        // having composite frequencies
        if (!prime[it->second]) {
            product *= (it->first);
        }
    }

    return product;
}

// Driver code
int main()
{
    int arr[] = {1, 2, 3, 3, 2, 1, 3, 2, 1, 3, 3, 1, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << productOfElements(arr, n);
    return 0;
}

Output:

5

Time Complexity: O(n * log(log(n)))
Space Complexity: O(n)

Refer – Sum of elements in an array having composite frequency

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.