Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all Prime Length Palindromic Substrings in C++
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
#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
Advertisements