Count characters in a string whose ASCII values are prime | Python3 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 . ; 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
from math import sqrt NEW_LINE max_val = 257 NEW_LINE def PrimeCharacters ( s ) : NEW_LINE INDENT prime = [ True ] * ( max_val + 1 ) NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( max_val ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( prime [ ord ( s [ i ] ) ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " ; NEW_LINE print ( PrimeCharacters ( S ) ) NEW_LINE DEDENT