Encuentre la suma de los valores ascii de los caracteres que están presentes en las posiciones principales

Dada la string str de tamaño N , la tarea es encontrar la suma de todos los valores ASCII de los caracteres que están presentes en las posiciones principales.
Ejemplos: 
 

Entrada: str = “abcdef” 
Salida: 298 
‘b’, ‘c’ y ‘e’ son los únicos caracteres que están 
en posiciones principales, es decir, 2, 3 y 5 respectivamente. 
Y la suma de sus valores ASCII es 298.
Entrada: str = «geeksforgeeks» 
Salida: 644 
 

Enfoque: un enfoque eficiente es atravesar toda la string y encontrar si la posición particular es prima o no. Si la posición del carácter actual es principal, agregue el valor ASCII del carácter a la respuesta.
A continuación se muestra la implementación del enfoque anterior: 
 

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>
Producción: 

644

 

Complejidad de tiempo: O(n*sqrt(n)), donde n representa el tamaño de la string dada.
Espacio auxiliar: O(1), no se requiere espacio adicional, por lo que es una constante.

Publicación traducida automáticamente

Artículo escrito por pawan_asipu y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *