Prime String in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string. Our task is to print YES / NO based on is the sum of ASCII values of the characters of the string is prime or not.

ASCII values are character encodings

Prime number is a number that is divisible only by the number itself and 1.

Let’s take an example to understand the problem,

Input: string = “Hello”
Output:No

To solve this problem, we will have to find the sum of ASCII values of all characters of the string. And store the sum in a variable and then check if the sum is a prime number or not.

The code to show the implementation of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
bool CheckPrimeString(string str) {
   int len = str.length(), sum = 0;
   for (int i = 0; i < len; i++)
   sum += (int)str[i];
   if (sum<= 1)
      return false;
   if (sum <= 3)
      return true;
   if (sum % 2 == 0 || sum % 3 == 0)
      return false;
   for (int i = 5; i * i <= sum; i = i + 6)
      if (sum % i == 0 || sum % (i + 2) == 0)
   return false;
   return true;
}
int main() {
   string str = "Hello!";
   cout<<"The string '"<<str<<" ' is ";
   if (CheckPrimeString(str))
      cout<<"a prime String \n";
   else
      cout<<"not a prime String\n";
}

Output

The string 'Hello! ' is not a prime String
raja
Published on 03-Feb-2020 15:04:08
Advertisements