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