1. 背景:原题链接:http://acm.uestc.edu.cn/#/problem/show/187
The number 151 is a prime palindrome because it is both a prime number and a palindrome (it is the same number when read forward as backward). Write a program that finds all prime palindromes in the range of two supplied numbers a and b ( 5≤a<b≤100,000,000 ); both a and b are considered to be within the range .
Input
Line 1 : Two integers, a and b
Output
The list of palindromic primes in numerical order, one per line.
2. 分析:求闭区间[a, b]中的回文素数,此题考查"T"。
在碰到求素数或者一些有关时间限制时候,尽量剪枝,素数问题中应当“打表法”,且多做限界。
此处,“唉筛求素数”
void is_prime() {
FOR(i, 2, MAXNum) {
if(isPrime[i] == 0) {
for(int j = i+i; j < MAXNum; j += i) {
isPrime[j] = 1;
}
}
}
}
3. 注意:原题中范围是到100000000, 但是1 0000000以上只有100000007为素数,但不是素数,因此可以大大剪枝。
回文就是将数字放在数组中,从0-n/2进行数组判等。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
//#include <map>
//#include <cmath>
//#include <queue>
//#include <stack>
//#define PB push_back
//#define PF pop_front
//#define sc1(x) scanf("%s",&(x))
#define sc(x) scanf("%d",&(x))
#define sc2(x,y) scanf("%d%d", &(x), &(y))
//#define sc3(x,y, z) scanf("%d%d%d", &(x), &(y), &(z))
#define pf(x) printf("%d\n", x);
//#define p(x) printf("%d ", x)
//#define P printf("\n")
//#define pf2(x, y) printf("%d %d\n", x, y)
#define FOR(i,b,e) for(int i=b; i<=e; i++)
#define FOR1(i,b,e) for(int i=b; i>=e; i--)
//#define FOR1(i,b,e) for(int i=b; i>e; i--)
#define CL(x,y) memset(x,y,sizeof(x))
using namespace std;
//const int MAXN = 100000000;
const int MAXNum = 10000000; // < 100000000, 只有100000007为素数
int a, b, arr[8], len;
int palindrome(int num);
int is_palindrome();
void is_prime();
bool isPrime[MAXNum];
int main() {
CL(isPrime, 0);
is_prime();
sc2(a, b);
FOR(i, a, b) {
// 剪枝
if(i>9989899)
break;
if(!isPrime[i] && palindrome(i)) {
pf(i);
}
}
return 0;
}
int palindrome(int num) {
if(num < 10)
return 1;
else {
int x = num;
len = 0;
FOR(i, 0, 7) {
arr[i] = x % 10;
x = x / 10;
len++;
// cout << num << endl;
if(x == 0)
break;
}
}
return is_palindrome();
}
int is_palindrome() {
FOR(i, 0, len / 2) {
if(arr[i] != arr[len-1-i]) {
return 0;
}
}
return 1;
}
void is_prime() {
FOR(i, 2, MAXNum) {
if(isPrime[i] == 0) {
for(int j = i+i; j < MAXNum; j += i) {
isPrime[j] = 1;
}
}
}
}