text: Sum and Product of Prime Frequencies of Characters in a String | C ++ program to find Sum and product of Prime Frequencies of Characters in a String ; 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 find the sum of prime frequencies of the characters of the given string ; map is used to store character frequencies ; Traverse the map ; If the frequency is prime ; 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 ; } } } void sumProdOfPrimeFreq ( string s ) { bool prime [ s . length ( ) + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , s . length ( ) + 1 ) ; int i , j ; unordered_map < char , int > m ; for ( i = 0 ; i < s . length ( ) ; i ++ ) m [ s [ i ] ] ++ ; int sum = 0 , product = 1 ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; it ++ ) { if ( prime [ it -> second ] ) { sum += it -> second ; product *= it -> second ; } } cout << " Sum ▁ = ▁ " << sum ; cout << " Product = " } int main ( ) { string s = " geeksforgeeks " ; sumProdOfPrimeFreq ( s ) ; return 0 ; }