Skip to content
Related Articles

Related Articles

Improve Article

Sum of elements in an array having composite frequency

  • Last Updated : 21 May, 2021

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 compsoite. So, the answer is 0. 
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :