Open In App

Sum of elements in an array having composite frequency

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of integers arr of size N, the task is to find the sum of the elements which have composite frequencies in the array.
Examples: 
 

Input: arr[] = {1, 2, 1, 1, 1, 3, 3, 2} 
Output:
1 appears 4 times which is a composite. All other elements 2 and 3 appears 2 times which is prime. So, the answer is just 1.
Input: arr[] = {4, 6, 7} 
Output:
All elements 4, 6 and 7 appears 1 times which is neither prime nor composite. So, the answer is 0. 
 

Approach: 
 

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

Below is the implementation of the above approach: 
 

C++




// C++ program to find sum of elements
// in an array having composite frequency
#include <bits/stdc++.h>
using namespace std;
#define N 100005
 
// Function to create
// Sieve to check primes
void SieveOfEratosthenes(
    vector<bool>& composite)
{
    for (int i = 0; i < N; i++)
        composite[i] = false;
 
    for (int p = 2; p * p < N; p++) {
 
        // If composite[p] is not changed,
        // then it is a prime
        if (!composite[p]) {
 
            // Update all multiples of p,
            // set them to composite
            for (int i = p * 2; i < N; i += p)
                composite[i] = true;
        }
    }
}
 
// Function to return the sum of elements
// in an array having composite frequency
int sumOfElements(
    int arr[], int n)
{
    vector<bool> composite(N);
 
    SieveOfEratosthenes(composite);
 
    // Map is used to store
    // element frequencies
    unordered_map<int, int> m;
    for (int i = 0; i < n; i++)
        m[arr[i]]++;
 
    // To store sum
    int sum = 0;
 
    // Traverse the map using iterators
    for (auto it = m.begin();
         it != m.end(); it++) {
 
        // Count the number of elements
        // having composite frequencies
        if (composite[it->second]) {
            sum += (it->first);
        }
    }
 
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 1, 1, 1,
                  3, 3, 2, 4 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << sumOfElements(arr, n);
 
    return 0;
}


Java




// Java program to find sum of elements
// in an array having composite frequency
import java.util.*;
 
class GFG{
static final int N = 10005;
 
// Function to create
// Sieve to check primes
static void SieveOfEratosthenes(Vector<Boolean> composite)
{
    for (int i = 0; i < N; i++)
    {
        composite.add(i, false);
    }
 
    for (int p = 2; p * p < N; p++) {
 
        // If composite[p] is not changed,
        // then it is a prime
        if (!composite.get(p)) {
 
            // Update all multiples of p,
            // set them to composite
            for (int i = p * 2; i < N; i += p) {
                composite.add(i, true);
            }
        }
    }
}
 
// Function to return the sum of elements
// in an array having composite frequency
static int sumOfElements(int arr[], int n)
{
    Vector<Boolean> composite = new Vector<Boolean>();
    for (int i = 0; i < N; i++)
        composite.add(false);
    SieveOfEratosthenes(composite);
 
    // Map is used to store
    // element frequencies
    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
    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);
        }
 
    // To store sum
    int sum = 0;
 
    // Traverse the map using iterators
    for (Map.Entry<Integer,Integer> it : mp.entrySet()){
 
        // Count the number of elements
        // having composite frequencies
        if (composite.get(it.getValue())) {
            sum += (it.getKey());
        }
    }
 
    return sum;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 1, 1, 1,
                3, 3, 2, 4 };
 
    int n = arr.length;
 
    // Function call
    System.out.print(sumOfElements(arr, n));
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 program to find sum of elements
# in an array having composite frequency
 
N = 100005
 
# Function to create
# Sieve to check primes
def SieveOfEratosthenes(composite):
 
    for p in range(2, N):
        if p*p > N:
            break
 
        # If composite[p] is not changed,
        # then it is a prime
        if (composite[p] == False):
 
            # Update all multiples of p,
            # set them to composite
            for i in range(2*p, N, p):
                composite[i] = True
 
# Function to return the sum of elements
# in an array having composite frequency
def sumOfElements(arr, n):
    composite = [False] * N
 
    SieveOfEratosthenes(composite)
 
    # Map is used to store
    # element frequencies
    m = dict();
    for i in range(n):
        m[arr[i]] = m.get(arr[i], 0) + 1
 
    # To store sum
    sum = 0
 
    # Traverse the map using iterators
    for it in m:
 
        # Count the number of elements
        # having composite frequencies
        if (composite[m[it]]):
            sum += (it)
 
    return sum
 
# Driver code
if __name__ == '__main__':
    arr=[1, 2, 1, 1, 1,3, 3, 2, 4]
 
    n = len(arr)
 
    # Function call
    print(sumOfElements(arr, n))
 
# This code is contributed by mohit kumar 29


C#




// C# program to find sum of elements
// in an array having composite frequency
using System;
using System.Collections.Generic;
 
class GFG{
static readonly int N = 10005;
  
// Function to create
// Sieve to check primes
static void SieveOfEratosthenes(List<Boolean> composite)
{
    for (int i = 0; i < N; i++)
    {
        composite.Insert(i, false);
    }
  
    for (int p = 2; p * p < N; p++) {
  
        // If composite[p] is not changed,
        // then it is a prime
        if (!composite[p]) {
  
            // Update all multiples of p,
            // set them to composite
            for (int i = p * 2; i < N; i += p) {
                composite.Insert(i, true);
            }
        }
    }
}
  
// Function to return the sum of elements
// in an array having composite frequency
static int sumOfElements(int []arr, int n)
{
    List<Boolean> composite = new List<Boolean>();
    for (int i = 0; i < N; i++)
        composite.Add(false);
    SieveOfEratosthenes(composite);
  
    // Map is used to store
    // element frequencies
    Dictionary<int,int> mp = new Dictionary<int,int>();
    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);
        }
  
    // To store sum
    int sum = 0;
  
    // Traverse the map using iterators
    foreach (KeyValuePair<int,int> it in mp){
  
        // Count the number of elements
        // having composite frequencies
            if (composite[it.Value]) {
                sum += (it.Key);
        }
    }
  
    return sum;
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 1, 1, 1,
                3, 3, 2, 4 };
  
    int n = arr.Length;
  
    // Function call
    Console.Write(sumOfElements(arr, n));
}
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript program to find sum of elements
// in an array having composite frequency
 
 
let N = 100005
 
// Function to create
// Sieve to check primes
function SieveOfEratosthenes(composite)
{
    for (let i = 0; i < N; i++)
        composite[i] = false;
 
    for (let p = 2; p * p < N; p++) {
 
        // If composite[p] is not changed,
        // then it is a prime
        if (!composite[p]) {
 
            // Update all multiples of p,
            // set them to composite
            for (let i = p * 2; i < N; i += p)
                composite[i] = true;
        }
    }
}
 
// Function to return the sum of elements
// in an array having composite frequency
function sumOfElements(arr, n)
{
    let composite = new Array(N);
 
    SieveOfEratosthenes(composite);
    // Map is used to store
    // element frequencies
    let m = new Map();
 
    for (let i = 0; i < n; i++)
    if(m.has(arr[i])){
        m[arr[i]] =  m[arr[i]] + 1;
    }
    else{
        m.set(arr[i], 1);
    }
 
    // To store sum
    let sum = 0;
 
    // Traverse the map using iterators
         
        m.forEach((value, key)=>{
            // Count the number of elements
            // having composite frequencies
                if (composite[key]) {
                    sum += value;
            }
      })
 
    return sum;
}
 
// Driver code
 
let arr = [ 1, 2, 1, 1, 1,
            3, 3, 2, 4 ];
 
let n = arr.length;
 
// Function call
document.write(sumOfElements(arr, n));
 
 
// This code is contributed by gfgking
 
</script>


Output

1






Time Complexity: O(N3/2)

Auxiliary Space: O(N)

Approach: Hashing

In this approach, we can make use of a hash map to store the frequency of each element in the array. Then, we can iterate through the hash map and check which elements have a composite frequency and add their value to the final sum.

Steps:

  1. Create a hash map to store the frequency of each element in the array.
  2. Traverse the array and update the frequency of each element in the hash map.
  3. Traverse the hash map and check which elements have a composite frequency.
  4. If an element has a composite frequency, add its value to the final sum.
  5. Return the final sum.

C++




#include <bits/stdc++.h>
#include <unordered_map>
#include <cmath>
 
using namespace std;
 
bool is_composite(int n) {
     
    //Returns True if n is a composite number, False otherwise.
    if (n < 4) {
        return false;
    }
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return true;
        }
    }
    return false;
}
 
int sum_of_composite_frequencies(vector<int> arr) {
     
    //Returns the sum of the elements which have
    //composite frequencies in the given array.
    unordered_map<int, int> freq;
    for (int num : arr) {
        freq[num]++;
    }
    int composite_freq_sum = 0;
    for (auto it = freq.begin(); it != freq.end(); it++) {
        if (is_composite(it->second)) {
            composite_freq_sum += it->first;
        }
    }
    return composite_freq_sum;
}
 
int main() {
    //Sample 1
    vector<int> arr1 = {1, 2, 1, 1, 1, 3, 3, 2};
    cout << sum_of_composite_frequencies(arr1) << endl;
 
    //Sample 2
    vector<int> arr2 = {4, 6, 7};
    cout << sum_of_composite_frequencies(arr2) << endl;
 
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
 
public class Main {
    public static boolean isComposite(int n)
    {
        // Returns true if n is a composite number, false
        // otherwise.
        if (n < 4) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return true;
            }
        }
        return false;
    }
 
    public static int
    sumOfCompositeFrequencies(Vector<Integer> arr)
    {
        // Returns the sum of the elements which have
        // composite frequencies in the given array.
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }
        int compositeFreqSum = 0;
        for (Map.Entry<Integer, Integer> entry :
             freq.entrySet()) {
            if (isComposite(entry.getValue())) {
                compositeFreqSum += entry.getKey();
            }
        }
        return compositeFreqSum;
    }
 
    public static void main(String[] args)
    {
        // Sample 1
        Vector<Integer> arr1 = new Vector<>();
        arr1.add(1);
        arr1.add(2);
        arr1.add(1);
        arr1.add(1);
        arr1.add(1);
        arr1.add(3);
        arr1.add(3);
        arr1.add(2);
        System.out.println(sumOfCompositeFrequencies(arr1));
 
        // Sample 2
        Vector<Integer> arr2 = new Vector<>();
        arr2.add(4);
        arr2.add(6);
        arr2.add(7);
        System.out.println(sumOfCompositeFrequencies(arr2));
    }
}
// This code is contributed by Samim Hossain Mondal.


Python3




def is_composite(n):
    """
    Returns True if n is a composite number, False otherwise.
    """
    if n < 4:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return True
    return False
 
def sum_of_composite_frequencies(arr):
    """
    Returns the sum of the elements which have
    composite frequencies in the given array.
    """
    freq = {}
    for num in arr:
        freq[num] = freq.get(num, 0) + 1
    composite_freq_sum = 0
    for key, value in freq.items():
        if is_composite(value):
            composite_freq_sum += key
    return composite_freq_sum
#Sample 1
arr = [1, 2, 1, 1, 1, 3, 3, 2]
print(sum_of_composite_frequencies(arr))
 
#Sample 2
arr = [4, 6, 7]
print(sum_of_composite_frequencies(arr))


C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
    public static bool IsComposite(int n)
    {
        // Returns true if n is a composite number, false otherwise.
        if (n < 4)
        {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(n); i++)
        {
            if (n % i == 0)
            {
                return true;
            }
        }
        return false;
    }
 
    public static int SumOfCompositeFrequencies(List<int> arr)
    {
        // Returns the sum of the elements which have composite frequencies in the given array.
        Dictionary<int, int> freq = new Dictionary<int, int>();
        foreach (int num in arr)
        {
            if (freq.ContainsKey(num))
            {
                freq[num]++;
            }
            else
            {
                freq[num] = 1;
            }
        }
        int compositeFreqSum = 0;
        foreach (KeyValuePair<int, int> entry in freq)
        {
            if (IsComposite(entry.Value))
            {
                compositeFreqSum += entry.Key;
            }
        }
        return compositeFreqSum;
    }
 
    public static void Main(string[] args)
    {
        // Sample 1
        List<int> arr1 = new List<int>
        {
            1, 2, 1, 1, 1, 3, 3, 2
        };
        Console.WriteLine(SumOfCompositeFrequencies(arr1));
 
        // Sample 2
        List<int> arr2 = new List<int>
        {
            4, 6, 7
        };
        Console.WriteLine(SumOfCompositeFrequencies(arr2));
    }
}


Javascript




function is_composite(n) {
    /*
    Returns True if n is a composite number, False otherwise.
    */
    if (n < 4) {
        return false;
    }
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i == 0) {
            return true;
        }
    }
    return false;
}
 
function sum_of_composite_frequencies(arr) {
    /*
    Returns the sum of the elements which have
    composite frequencies in the given array.
    */
    let freq = {};
    for (let num of arr) {
        freq[num] = (freq[num] || 0) + 1;
    }
    let composite_freq_sum = 0;
    for (let [key, value] of Object.entries(freq)) {
        if (is_composite(value)) {
            composite_freq_sum += parseInt(key);
        }
    }
    return composite_freq_sum;
}
 
// Sample 1
let arr = [1, 2, 1, 1, 1, 3, 3, 2];
console.log(sum_of_composite_frequencies(arr));
 
// Sample 2
arr = [4, 6, 7];
console.log(sum_of_composite_frequencies(arr));


Output

1
0






Time Complexity: O(N log log N), where N is the size of the input array. 

Auxiliary Space: O(N), where N is the size of the input array. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads