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