Count all Prime Length Palindromic Substrings | C ++ implementation of the approach ; Function that returns true if sub - string starting at i and ending at j in str is a palindrome ; Function to count all palindromic substring whose lwngth is a prime number ; 0 and 1 are non - primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; To store the required number of sub - strings ; Starting from the smallest prime till the largest length of the sub - string possible ; If j is prime ; Check all the sub - strings of length j ; If current sub - string is a palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str , int i , int j ) { while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } int countPrimePalindrome ( 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 ( isPalindrome ( str , i , i + j - 1 ) ) count ++ ; } } } return count ; } int main ( ) { string s = " geeksforgeeks " ; int len = s . length ( ) ; cout << countPrimePalindrome ( s , len ) ; return 0 ; }