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 ; Count the number of elements having prime frequencies ; Driver code
using System ; using System . Collections . Generic ; class GFG { static 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 ; } } } static int sumOfElements ( int [ ] arr , int n ) { bool [ ] prime = new bool [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , n + 1 ) ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( arr [ i ] ) ) { var val = m [ arr [ i ] ] ; m . Remove ( arr [ i ] ) ; m . Add ( arr [ i ] , val + 1 ) ; } else { m . Add ( arr [ i ] , 1 ) ; } } int sum = 0 ; foreach ( KeyValuePair < int , int > entry in m ) { int key = entry . Key ; int value = entry . Value ; if ( prime [ value ] ) { sum += ( key ) ; } } return sum ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 4 , 6 , 5 , 4 , 6 } ; int n = arr . Length ; Console . WriteLine ( sumOfElements ( arr , n ) ) ; } }