程序代码:
#include<iostream>
#include<vector>
#include<time.h>
using namespace std;
class PrimePalindrome
{
public:
void PrimeNumbers();
void PalindromeNumbers();
void showNumbers();
void inputNum();
private:
int beginNum;
int endNum;
vector<int> palindrome;
vector<int> palindromePrime;
};
void PrimePalindrome::PalindromeNumbers()
{
int s, y = 0;
for (int i = beginNum; i <= endNum;i++)
{
if (i>2 && i%2 == 0)
continue;
s = i;
while (s > 0)
{
y = y * 10 + s % 10;
s = s / 10;
}
if (y==i)
{
palindrome.push_back(i);
}
y = 0;
}
}
void PrimePalindrome::PrimeNumbers()
{
int a = 0;
int i;
auto itr = palindrome.begin();
for (itr; itr != palindrome.end(); ++itr)
{
for (i = 2; i <= (*itr);++i)
{
if ((*itr) % i == 0)
break;
}
if (i == (*itr)){
palindromePrime.push_back(*itr);
}
}
}
void PrimePalindrome::showNumbers()
{
cout << "回文素数列表:" << endl;
for (auto itr = palindromePrime.begin(); itr != palindromePrime.end();++itr)
{
cout << *itr << endl;
}
}
void PrimePalindrome::inputNum()
{
cout << "Input the beginNum : ";
cin >> beginNum;
while (!getchar());
cout << "Input the endNum : ";
cin >> endNum;
while (!getchar());
}
int main()
{
clock_t start, finish;
double totaltime;
PrimePalindrome pp;
pp.inputNum();
start = clock();
pp.PalindromeNumbers();
pp.PrimeNumbers();
pp.showNumbers();
finish = clock();
totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "\n此程序的运行时间为" << totaltime << "秒!" << endl;
getchar();
}
测试范围2-100000,内存占用804K(任务管理器显示)