Open In App

Count characters in a string whose ASCII values are prime

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime.

Examples: 

Input: S = "geeksforgeeks" 
Output :
'g', 'e' and 'k' are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively.

Input: S = "abcdefghijklmnopqrstuvwxyz" 
Output:

Approach: The idea is to generate all primes up to the max ASCII value of the character of string S using the Sieve of Eratosthenes. Now, Iterate the string and get the ASCII value of each character. If the ASCII value is prime then increment the count. Finally, print the count.

Below is the implementation of the above approach: 

C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
#define max_val 257

// Function to find prime characters in the string
int PrimeCharacters(string s)
{

    // 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.
    vector<bool> prime(max_val + 1, true);

    // 0 and 1 are not primes
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= max_val; p++) {

        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {

            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime[i] = false;
        }
    }

    int count = 0;

    // Traverse all the characters
    for (int i = 0; i < s.length(); ++i) {
        if (prime[int(s[i])])
            count++;
    }

    return count;
}

// Driver program
int main()
{
    string S = "geeksforgeeks";

    // print required answer
    cout << PrimeCharacters(S);

    return 0;
}
Java Python3 C# JavaScript

Output
8

Complexity Analysis:

  • Time Complexity: O(max_val*log(log(max_val)))
  • Auxiliary Space: O(max_val)

Article Tags :
Practice Tags :

Similar Reads