Related Articles

# Count all Prime Length Palindromic Substrings

• Last Updated : 25 May, 2021

Given string str, the task is to count all the sub-strings of str which are palindromes and their length is prime.

Examples:

Input: str = “geeksforgeeks”
Output:
“ee” and “ee” are the only valid sub-strings.

Input: str = “abccc”
Output:

Approach: Using Sieve of Eratosthenes, find all the primes till the length of str because that is the maximum length a sub-string of str can have. Now starting from the smallest prime i.e. j = 2 till j ≤ len(str). If j is prime then count all the palindromic sub-strings of str whose length = j. Print the total count at the end.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;` `// Function that returns true if sub-string``// starting at i and ending at j in str is a palindrome``bool` `isPalindrome(string str, ``int` `i, ``int` `j)``{``    ``while` `(i < j) {``        ``if` `(str[i] != str[j])``            ``return` `false``;``        ``i++;``        ``j--;``    ``}` `    ``return` `true``;``}` `// Function to count all palindromic substring``// whose lwngth is a prime number``int` `countPrimePalindrome(string str, ``int` `len)``{` `    ``bool` `prime[len + 1];``    ``memset``(prime, ``true``, ``sizeof``(prime));` `    ``// 0 and 1 are non-primes``    ``prime = prime = ``false``;``    ``for` `(``int` `p = 2; p * p <= len; p++) {` `        ``// If prime[p] is not changed, then it is a prime``        ``if` `(prime[p]) {` `            ``// 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.``            ``for` `(``int` `i = p * p; i <= len; i += p)``                ``prime[i] = ``false``;``        ``}``    ``}` `    ``// To store the required number of sub-strings``    ``int` `count = 0;` `    ``// Starting from the smallest prime till``    ``// the largest length of the sub-string possible``    ``for` `(``int` `j = 2; j <= len; j++) {` `        ``// If j is prime``        ``if` `(prime[j]) {` `            ``// Check all the sub-strings of length j``            ``for` `(``int` `i = 0; i + j - 1 < len; i++) {` `                ``// If current sub-string is a palindrome``                ``if` `(isPalindrome(str, i, i + j - 1))``                    ``count++;``            ``}``        ``}``    ``}` `    ``return` `count;``}` `// Driver Code``int` `main()``{``    ``string s = ``"geeksforgeeks"``;``    ``int` `len = s.length();` `    ``cout << countPrimePalindrome(s, len);` `    ``return` `0;``}`

## Java

 `// Java implementation of the approach``import` `java.util.Arrays;` `class` `GfG``{` `    ``// Function that returns true if``    ``// sub-string starting at i and``    ``// ending at j in str is a palindrome``    ``static` `boolean` `isPalindrome(String str, ``int` `i, ``int` `j)``    ``{``        ``while` `(i < j)``        ``{``            ``if` `(str.charAt(i) != str.charAt(j))``                ``return` `false``;``            ``i++;``            ``j--;``        ``}``    ` `        ``return` `true``;``    ``}``    ` `    ``// Function to count all palindromic substring``    ``// whose lwngth is a prime number``    ``static` `int` `countPrimePalindrome(String str, ``int` `len)``    ``{``    ` `        ``boolean``[] prime = ``new` `boolean``[len + ``1``];``        ``Arrays.fill(prime, ``true``);``    ` `        ``// 0 and 1 are non-primes``        ``prime[``0``] = prime[``1``] = ``false``;``        ``for` `(``int` `p = ``2``; p * p <= len; p++)``        ``{``    ` `            ``// If prime[p] is not changed,``            ``// then it is a prime``            ``if` `(prime[p])``            ``{``    ` `                ``// 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.``                ``for` `(``int` `i = p * p; i <= len; i += p)``                    ``prime[i] = ``false``;``            ``}``        ``}``    ` `        ``// To store the required number of sub-strings``        ``int` `count = ``0``;``    ` `        ``// Starting from the smallest prime till``        ``// the largest length of the sub-string possible``        ``for` `(``int` `j = ``2``; j <= len; j++)``        ``{``    ` `            ``// If j is prime``            ``if` `(prime[j])``            ``{``    ` `                ``// Check all the sub-strings of length j``                ``for` `(``int` `i = ``0``; i + j - ``1` `< len; i++)``                ``{``    ` `                    ``// If current sub-string is a palindrome``                    ``if` `(isPalindrome(str, i, i + j - ``1``))``                        ``count++;``                ``}``            ``}``        ``}``        ``return` `count;``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `main(String []args)``    ``{``        ``String s = ``"geeksforgeeks"``;``        ``int` `len = s.length();` `        ``System.out.println(countPrimePalindrome(s, len));``    ``}``}` `// This code is contributed by Rituraj Jain`

## Python3

 `# Python3 implementation of the approach``import` `math as mt` `# Function that returns True if sub-str1ing``# starting at i and ending at j in str1``# is a palindrome``def` `isPalindrome(str1, i, j):` `    ``while` `(i < j):``        ``if` `(str1[i] !``=` `str1[j]):``            ``return` `False``        ``i ``+``=` `1``        ``j ``-``=` `1``    ` `    ``return` `True``    ` `# Function to count all palindromic substr1ing``# whose lwngth is a prime number``def` `countPrimePalindrome(str1, ``Len``):` `    ``prime ``=` `[``True` `for` `i ``in` `range``(``Len` `+` `1``)]` `    ``# 0 and 1 are non-primes``    ``prime[``0``], prime[``1``] ``=` `False``, ``False``    ``for` `p ``in` `range``(``2``, mt.ceil(mt.sqrt(``Len` `+` `1``))):` `        ``# If prime[p] is not changed,``        ``# then it is a prime``        ``if` `(prime[p]):` `            ``# 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.``            ``for` `i ``in` `range``(``2` `*` `p, ``Len` `+` `1``, p):``                ``prime[i] ``=` `False``        ` `    ``# To store the required number``    ``# of sub-str1ings``    ``count ``=` `0` `    ``# Starting from the smallest prime``    ``# till the largest Length of the``    ``# sub-str1ing possible``    ``for` `j ``in` `range``(``2``, ``Len` `+` `1``):` `        ``# If j is prime``        ``if` `(prime[j]):` `            ``# Check all the sub-str1ings of``            ``# Length j``            ``for` `i ``in` `range``(``Len` `+` `1` `-` `j):` `                ``# If current sub-str1ing is a palindrome``                ``if` `(isPalindrome(str1, i, i ``+` `j ``-` `1``)):``                    ``count ``+``=` `1``            ` `    ``return` `count` `# Driver Code``s ``=` `"geeksforgeeks"``Len` `=` `len``(s)` `print``( countPrimePalindrome(s, ``Len``))` `# This code is contributed by``# Mohit kumar 29`

## C#

 `// C# implementation of the approach``using` `System;` `class` `GfG``{` `// Function that returns true if``// sub-string starting at i and``// ending at j in str is a palindrome``static` `bool` `isPalindrome(``string` `str,``                         ``int` `i, ``int` `j)``{``    ``while` `(i < j)``    ``{``        ``if` `(str[i] != str[j])``            ``return` `false``;``        ``i++;``        ``j--;``    ``}` `    ``return` `true``;``}` `// Function to count all palindromic``// substring whose lwngth is a prime number``static` `int` `countPrimePalindrome(``string` `str,``                                ``int` `len)``{` `    ``bool``[] prime = ``new` `bool``[len + 1];``    ``Array.Fill(prime, ``true``);` `    ``// 0 and 1 are non-primes``    ``prime = prime = ``false``;``    ``for` `(``int` `p = 2; p * p <= len; p++)``    ``{` `        ``// If prime[p] is not changed,``        ``// then it is a prime``        ``if` `(prime[p])``        ``{` `            ``// 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.``            ``for` `(``int` `i = p * p; i <= len; i += p)``                ``prime[i] = ``false``;``        ``}``    ``}` `    ``// To store the required number``    ``// of sub-strings``    ``int` `count = 0;` `    ``// Starting from the smallest prime``    ``// till the largest length of the``    ``// sub-string possible``    ``for` `(``int` `j = 2; j <= len; j++)``    ``{` `        ``// If j is prime``        ``if` `(prime[j])``        ``{` `            ``// Check all the sub-strings of``            ``// length j``            ``for` `(``int` `i = 0;``                     ``i + j - 1 < len; i++)``            ``{` `                ``// If current sub-string is a``                ``// palindrome``                ``if` `(isPalindrome(str, i, i + j - 1))``                    ``count++;``            ``}``        ``}``    ``}``    ``return` `count;``}` `// Driver code``public` `static` `void` `Main()``{``    ``string` `s = ``"geeksforgeeks"``;``    ``int` `len = s.Length;` `    ``Console.WriteLine(countPrimePalindrome(s, len));``}``}` `// This code is contributed by Code_Mech`

## PHP

 ``

## Javascript

 ``
Output:
`2`

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up