hint1就是解决问题的关键:Generate the palindromes and see if they are prime.
有目的的生成要比无目的逐一验证更有效率,当然前提是得存在有效的生成方法。
/* ID:chenjiong PROG:pprime LANG:C++ */ #include <stdio.h> #include <string.h> #include <math.h> const int MAXN = 20000; int palin[MAXN]; int cnt; int a,b; void p1() { palin[cnt++] = 5; palin[cnt++] = 7; } void p2() { palin[cnt++] = 11; } void p3() { int i,j; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) palin[cnt++] = i * 100 + j * 10 + i; } void p4() { int i,j; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) palin[cnt++] = i * 1000 + j * 100 + j * 10 + i; } void p5() { int i,j,k; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) for ( k = 0; k <= 9; k++) palin[cnt++] = i * 10000 + j * 1000 + k * 100 + j * 10 + i; } void p6() { int i,j,k; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) for ( k = 0; k <= 9; k++) palin[cnt++] = i * 100000 + j * 10000 + k * 1000 + k * 100 + j * 10 + i; } void p7() { int i,j,k,w; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) for ( k = 0; k <= 9; k++) for ( w = 0; w <= 9; w++) palin[cnt++] = i * 1000000 + j * 100000 + k * 10000 + w * 1000 + k * 100 + j * 10 + i; } void p8() { int i,j,k,w; for ( i = 1; i <= 9; i += 2) for ( j = 0; j <= 9; j++) for ( k = 0; k <= 9; k++) for ( w = 0; w <= 9; w++) palin[cnt++] = i * 10000000 + j * 1000000 + k * 100000 + w * 10000 + w * 1000 + k * 100 + j * 10 + i; } void palindrome(int x) { switch ( x ) { case 1 : p1(); break; case 2 : p2(); break; case 3 : p3(); break; case 4 : p4(); break; case 5 : p5(); break; case 6 : p6(); break; case 7 : p7(); break; case 8 : p8(); break; } } bool is_prime(int a) { if ( a == 1 ) return false; if ( a == 2 || a == 3 ) return true; if ( a % 2 == 0 ) return false; int i; for ( i = 3; i <= sqrt(a); i += 2) if ( a % i == 0 ) return false; return true; } int digit_num(int a) { int ans = 0; while ( a > 0 ) { a /= 10; ans++; } return ans; } int main() { freopen("pprime.in","r",stdin); freopen("pprime.out","w",stdout); scanf("%d%d",&a,&b); int s = digit_num(a); int d = digit_num(b); int i,j; cnt = 0; for ( i = s; i <= d; i++) palindrome(i); for ( j = 0; j < cnt; j++) { if ( a <= palin[j] && palin[j] <= b ) { if ( is_prime(palin[j]) ) printf("%d\n",palin[j]); } } return 0; }