Count characters in a string whose ASCII values are prime | JavaScript 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 Code ; print required answer
const max_val = 257 ; function PrimeCharacters ( s ) { var prime = new Array ( max_val + 1 ) ; for ( var i = 0 ; i <= max_val ; i ++ ) prime [ i ] = true ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( var p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] === true ) { for ( var i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } var count = 0 ; for ( var i = 0 ; i < s . length ; ++ i ) { if ( prime [ s [ i ] . charCodeAt ( 0 ) ] ) count ++ ; } return count ; } var S = " " ; document . write ( PrimeCharacters ( S ) ) ;