Open In App

Find the sum of the ascii values of characters which are present at prime positions

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str of size N, the task is to find the sum of all ASCII values of the characters that are present at prime positions.

Examples: 

Input: str = “abcdef” 
Output: 298 
‘b’, ‘c’ and ‘e’ are the only characters which are 
at prime positions i.e. 2, 3 and 5 respectively. 
And sum of their ASCII values is 298.
Input: str = “geeksforgeeks” 
Output: 644 

Approach: An efficient approach is to traverse through the whole string and find if the particular position is prime or not. If the position of the current character is prime then add the ASCII value of the character to the answer.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true
// if n is prime
bool isPrime(int n)
{
    if (n == 0 || n == 1)
        return false;
    for (int i = 2; i * i <= n; i++)
        if (n % i == 0)
            return false;
 
    return true;
}
 
// Function to return the sum
// of the ascii values of the characters
// which are present at prime positions
int sumAscii(string str, int n)
{
    // To store the sum
    int sum = 0;
 
    // For every character
    for (int i = 0; i < n; i++) {
 
        // If current position is prime
        // then add the ASCII value of the
        // character at the current position
        if (isPrime(i + 1))
            sum += (int)(str[i]);
    }
 
    return sum;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int n = str.size();
 
    cout << sumAscii(str, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function that returns true
    // if n is prime
    static boolean isPrime(int n)
    {
        if (n == 0 || n == 1)
        {
            return false;
        }
        for (int i = 2; i * i <= n; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Function to return the sum
    // of the ascii values of the characters
    // which are present at prime positions
    static int sumAscii(String str, int n)
    {
        // To store the sum
        int sum = 0;
 
        // For every character
        for (int i = 0; i < n; i++)
        {
 
            // If current position is prime
            // then add the ASCII value of the
            // character at the current position
            if (isPrime(i + 1))
            {
                sum += (int) (str.charAt(i));
            }
        }
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int n = str.length();
 
        System.out.println(sumAscii(str, n));
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 implementation of the approach
 
from math import sqrt
 
# Function that returns true
# if n is prime
def isPrime(n) :
     
    if (n == 0 or n == 1) :
        return False;
         
    for i in range(2, int(sqrt(n)) + 1) :
        if (n % i == 0):
            return False;
 
    return True;
 
 
# Function to return the sum
# of the ascii values of the characters
# which are present at prime positions
def sumAscii(string, n) :
 
    # To store the sum
    sum = 0;
 
    # For every character
    for i in range(n) :
 
        # If current position is prime
        # then add the ASCII value of the
        # character at the current position
        if (isPrime(i + 1)) :
            sum += ord(string[i]);
 
    return sum;
 
 
# Driver code
if __name__ == "__main__" :
 
    string = "geeksforgeeks";
    n = len(string);
 
    print(sumAscii(string, n));
 
# This code is contributed by AnkitRai01


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function that returns true
    // if n is prime
    static bool isPrime(int n)
    {
        if (n == 0 || n == 1)
        {
            return false;
        }
         
        for (int i = 2; i * i <= n; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
 
        return true;
    }
 
    // Function to return the sum
    // of the ascii values of the characters
    // which are present at prime positions
    static int sumAscii(string str, int n)
    {
        // To store the sum
        int sum = 0;
 
        // For every character
        for (int i = 0; i < n; i++)
        {
 
            // If current position is prime
            // then add the ASCII value of the
            // character at the current position
            if (isPrime(i + 1))
            {
                sum += (int) (str[i]);
            }
        }
 
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        int n = str.Length;
 
        Console.WriteLine(sumAscii(str, n));
    }
}
 
// This code contributed by anuj_67..


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function that returns true
// if n is prime
function isPrime(n)
{
    if (n == 0 || n == 1)
        return false;
    for (let i = 2; i * i <= n; i++)
        if (n % i == 0)
            return false;
 
    return true;
}
 
// Function to return the sum
// of the ascii values of the characters
// which are present at prime positions
function sumAscii(str, n)
{
    // To store the sum
    let sum = 0;
 
    // For every character
    for (let i = 0; i < n; i++) {
 
        // If current position is prime
        // then add the ASCII value of the
        // character at the current position
        if (isPrime(i + 1))
            sum += str.charCodeAt(i);
    }
 
    return sum;
}
 
// Driver code
    let str = "geeksforgeeks";
    let n = str.length;
 
    document.write(sumAscii(str, n));
 
</script>


Output

644

Time Complexity: O(n*sqrt(n)), where n represents the size of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Approach:  Sieve of Eratosthenes

Below is the implementation of the above approach:

C++




// c++ iMPLEMENTATION
#include <bits/stdc++.h>
using namespace std;
 
// Function to find sum of characters
// which are at prime position
int sumAscii(string str, int n) {
    bool prime[n+1];
    memset(prime, true, sizeof(prime));
    prime[0] = false;
    prime[1] = false;
    for(int i=2; i*i<=n; i++) {
        if(prime[i]) {
            for(int j=i*i; j<=n; j+=i) {
                prime[j] = false;
            }
        }
    }
    int sum = 0;
    for(int i=0; i<n; i++) {
        if(prime[i+1]) {
            sum += (int)str[i];
        }
    }
    return sum;
}
 
// Driver code
int main() {
    string str = "geeksforgeeks";
    int n = str.size();
   
      // Function call
    cout << sumAscii(str, n);
    return 0;
}


Java




import java.util.Arrays;
 
public class Main {
    public static int sumAscii(String str, int n) {
        // Create a boolean array to mark prime numbers
        boolean[] prime = new boolean[n + 1];
 
        // Initialize all elements as true initially
        Arrays.fill(prime, true);
 
        // Mark 0 and 1 as non-prime numbers
        prime[0] = false;
        prime[1] = false;
 
        // Sieve of Eratosthenes: Mark all multiples of primes as non-prime
        for (int i = 2; i * i <= n; i++) {
            if (prime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    prime[j] = false;
                }
            }
        }
 
        int sum = 0;
        // Calculate sum of ASCII values of characters at prime indices
        for (int i = 0; i < n; i++) {
            if (prime[i + 1]) {  // Check if the index is prime
                sum += (int) str.charAt(i);  // Add ASCII value of character at the prime index to the sum
            }
        }
 
        return sum;
    }
 
    public static void main(String[] args) {
        String str = "geeksforgeeks";
        int n = str.length();
 
        // Function call
        System.out.println(sumAscii(str, n));
    }
}


Python3




def sum_ascii(s):
    n = len(s)
    prime = [True] * (n + 1)
    prime[0] = prime[1] = False
 
    # Mark non-prime positions using the Sieve of Eratosthenes algorithm
    for i in range(2, int(n ** 0.5) + 1):
        if prime[i]:
            for j in range(i * i, n + 1, i):
                prime[j] = False
 
    sum_chars = 0
    for i in range(n):
        if prime[i + 1]:
            sum_chars += ord(s[i])  # Convert character to ASCII and add to sum
 
    return sum_chars
 
# Driver code
if __name__ == "__main__":
    string = "geeksforgeeks"
 
    # Function call
    print(sum_ascii(string))


C#




using System;
 
namespace PrimePositionSum
{
    class GFG
    {
        // Function to find sum of characters
        // which are at prime position
        static int SumAscii(string str, int n)
        {
            bool[] prime = new bool[n + 1];
            Array.Fill(prime, true);
            prime[0] = false;
            prime[1] = false;
 
            for (int i = 2; i * i <= n; i++)
            {
                if (prime[i])
                {
                    for (int j = i * i; j <= n; j += i)
                    {
                        prime[j] = false;
                    }
                }
            }
 
            int sum = 0;
            for (int i = 0; i < n; i++)
            {
                if (prime[i + 1])
                {
                    sum += (int)str[i];
                }
            }
 
            return sum;
        }
 
        // Main function
        static void Main(string[] args)
        {
            string str = "geeksforgeeks";
            int n = str.Length;
 
            // Function call
            Console.WriteLine(SumAscii(str, n));
        }
    }
}


Javascript




// Function to find sum of characters
// which are at prime position
function sumAscii(str) {
    const n = str.length;
    const prime = new Array(n + 1).fill(true);
    prime[0] = false;
    prime[1] = false;
    for (let i = 2; i * i <= n; i++) {
        if (prime[i]) {
            for (let j = i * i; j <= n; j += i) {
                prime[j] = false;
            }
        }
    }
    let sum = 0;
    for (let i = 0; i < n; i++) {
        if (prime[i + 1]) {
            sum += str.charCodeAt(i);
        }
    }
    return sum;
}
 
// Driver code
const str = "geeksforgeeks";
 
// Function call
console.log(sumAscii(str));


Output

644

Time Complexity: O(nlog(log(n)))
Auxiliary Space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads