text: Print characters having prime frequencies in order of occurrence | C ++ implementation of the approach ; 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 print the prime frequency characters in the order of their occurrence ; Function to create Sieve to check primes ; To store the frequency of each of the character of the string ; Initialize all elements of freq [ ] to 0 ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is prime ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE  26 NEW_LINE 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 printChar ( string str , int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , str . length ( ) + 1 ) ; int freq [ SIZE ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < n ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ freq [ str [ i ] - ' a ' ] ] ) { cout << str [ i ] ; } } } int main ( ) { string str = " geeksforgeeks " ; int n = str . length ( ) ; printChar ( str , n ) ; return 0 ; }