Count characters in a string whose ASCII values are prime | Java implementation of above approach ; Function to find prime characters in the String ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a Boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; initialize the value ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all the characters ; Driver program ; print required answer
class Solution { static final int max_val = 257 ; static int PrimeCharacters ( String s ) { boolean prime [ ] = new boolean [ max_val + 1 ] ; for ( int i = 0 ; i <= max_val ; i ++ ) prime [ i ] = true ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( prime [ ( int ) ( s . charAt ( i ) ) ] ) count ++ ; } return count ; } public static void main ( String args [ ] ) { String S = " geeksforgeeks " ; System . out . print ( PrimeCharacters ( S ) ) ; } }