Remove characters from given string whose frequencies are a Prime Number | Java program for the above approach ; Function to perform the seive of eratosthenes algorithm ; Initialize all entries in prime [ ] as true ; Initialize 0 and 1 as non prime ; Traversing the prime array ; If i is prime ; All multiples of i must be marked false as they are non prime ; Function to remove characters which have prime frequency in the String ; Length of the String ; Create a boolean array prime ; Sieve of Eratosthenes ; Stores the frequency of character ; Storing the frequencies ; New String that will be formed ; Removing the characters which have prime frequencies ; If the character has prime frequency then skip ; Else concatenate the character to the new String ; Print the modified String ; Driver Code ; Function Call
import java . util . * ; class GFG { static void SieveOfEratosthenes ( boolean [ ] prime , int n ) { for ( int i = 0 ; i <= n ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = 2 ; i * j <= n ; j ++ ) { prime [ i * j ] = false ; } } } } static void removePrimeFrequencies ( char [ ] s ) { int n = s . length ; boolean [ ] prime = new boolean [ n + 1 ] ; SieveOfEratosthenes ( prime , n ) ; HashMap < Character , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( m . containsKey ( s [ i ] ) ) { m . put ( s [ i ] , m . get ( s [ i ] ) + 1 ) ; } else { m . put ( s [ i ] , 1 ) ; } } String new_String = " " ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( prime [ m . get ( s [ i ] ) ] ) continue ; new_String += s [ i ] ; } System . out . print ( new_String ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; removePrimeFrequencies ( str . toCharArray ( ) ) ; } }