Count all Prime Length Palindromic Substrings in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the number of prime length palindromic strings.

For this we will be provided with a string. Our task is to count all the sub strings which are palindromes and have prime lengths.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//checking for a palindrome
bool if_palin(string str, int i, int j){
   while (i < j) {
      if (str[i] != str[j])
         return false;
      i++;
      j--;
   }
   return true;
}
//counting palindrome with prime length
int count_prime(string str, int len){
   bool prime[len + 1];
   memset(prime, true, sizeof(prime));
   prime[0] = prime[1] = false;
   for (int p = 2; p * p <= len; p++) {
      if (prime[p]) {
         for (int i = p * p; i <= len; i += p)
            prime[i] = false;
      }
   }
   int count = 0;
   for (int j = 2; j <= len; j++) {
      if (prime[j]) {
         for (int i = 0; i + j - 1 < len; i++) {
            if (if_palin(str, i, i + j - 1))
               count++;
         }
      }
   }
   return count;
}
int main(){
   string s = "abccc";
   int len = s.length();
   cout << count_prime(s, len);
   return 0;
}

Output

3
raja
Published on 17-Feb-2020 15:05:07
Advertisements