http://train.usaco.org/usacoprob2?a=dbjjBvzs5BK&S=pprime
题目大意:
找出a到b之间所有即使质数,又是回文数字的数
思路:
生成回文数字,判断是否是质数
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int creatpalindromes(int n, bool full)
{
int t = n;
if(!full) n /= 10;
while(n)
{
t = t*10 + n%10;
n /= 10;
}
return t;
}
bool isprime(int n)
{
for(int i = 2; i <= sqrt(n); i++)
if(n%i == 0) return false;
return true;
}
int main()
{
ifstream fin("pprime.in");
ofstream fout("pprime.out");
int a, b;
fin >> a >> b;
// for(int i = a; i <= b && i < 10000000; i++)
// if(ispalindromes(i) && isprime(i)) fout << i << endl; 超时。。。
int m = 1, t;
bool f = true;
for(int n = 1; n < 5 && f; n++, m *= 10)
{
for(int j = 0; j < 2 && f; j++)
{
for(int i = m; i < m*10 && f; i++)
{
t = creatpalindromes(i, j);
if(t <= b && t >= a && isprime(t)) fout << t << endl;
else if(t > b) f = false;
}
}
}
fout.close();
return 0;
}