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

10 May, 2021
Given string str of size N, the task is to find the sum of all ASCII values of the characters which 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++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true// if n is primebool 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 positionsint 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 codeint main(){    string str = "geeksforgeeks";    int n = str.size();     cout << sumAscii(str, n);     return 0;}
// Java implementation of the approachimport 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 implementation of the approach from math import sqrt # Function that returns true# if n is primedef 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 positionsdef 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 codeif __name__ == "__main__" :     string = "geeksforgeeks";    n = len(string);     print(sumAscii(string, n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing 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..
<script> // Javascript implementation of the approach // Function that returns true// if n is primefunction 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 positionsfunction 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>
644
 
Rajput-Ji
vt_m
ankthon
souravmahato348
ASCII
Prime Number
Competitive Programming
Mathematical
Strings
Strings
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bits manipulation (Important tactics)
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Breadth First Traversal ( BFS ) on a 2D array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7