计算C ++中所有素数回文子串
在本教程中,我们将讨论一个查找素数回文串数的程序。
为此,我们将提供一个字符串。我们的任务是计算所有属于回文且具有素数长度的子字符串。
示例
#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;
}输出结果
3
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短