Prime Palindromes
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 .
PROGRAM NAME: pprime
INPUT FORMAT
Line 1: | Two integers, a and b |
SAMPLE INPUT (file pprime.in)
5 500
OUTPUT FORMAT
The list of palindromic primes in numerical order, one per line.
SAMPLE OUTPUT (file pprime.out)
5 7 11 101 131 151 181 191 313 353 373 383
HINTS (use them carefully!)
题意:
给出a和b,表示a到b这个范围(5<=a<b<=100000000),输出在这个范围内的所有回文串素数。
思路:
暴搜,剪枝。
1.回文串数字的长度可能是1,2,3,4,5,6,7,8。但是长度为偶数的时候,一定能被11整除,故长度只可能是1,3,5,7,还有长度为2时的11;
2.回文串的首尾数字必须相同,那么首尾和末尾只能是1,3,7,9,还有当只有一位数的时候的5;
3.素数筛选,小于10000时直接判断,大于10000时用10000内的素数是否能整除这个数来判断。
AC:
/* TASK:pprime LANG:C++ ID:sum-g1 */ #include<stdio.h> #include<math.h> #include<string.h> int a,b; int pri[15000],prinum[15000],ans=0; int test(int num) //10000内的素数判断 { if(num == 1) return 0; for(int i = 2;i <= num/2;i += 1) if(!(num % i)) return 0; return 1; } int test2(int num) //10000外的素数判断 { for(int i = 0;i < ans;i++) { if(prinum[i] > num/2) break; if(!(num % prinum[i])) return 0; } return 1; } void pal() { for(int i = 1;i <= 9;i += 2) //1位 if(pri[i] && i <= b && i >= a) printf("%d\n",i); if(11 <= b && 11 >= a) printf("%d\n",11); //2位 for(int i = 1 ;i <= 9;i += 2) //3位 { if(i == 5) continue; for(int j = 0;j <= 9;j++) { int k = i * pow(10,2) + j * pow(10,1) + i * pow(10,0); if(k > b || k < a) continue; if(pri[k]) printf("%d\n",k); } } for(int i = 1 ;i <= 9;i += 2) //5位 { if(i == 5) continue; for(int j = 0;j <= 9;j++) for(int p = 0;p <= 9;p++) { int k = i * pow(10,4) + j * pow(10,3) + p * pow(10,2) + j * pow(10,1) + i * pow(10,0); if(k > b || k < a) continue; if(test2(k)) printf("%d\n",k); } } for(int i = 1 ;i <= 9;i += 2) //7位 { if(i == 5) continue; for(int j = 0;j <= 9;j++) for(int p = 0;p <= 9;p++) for(int q = 0;q <= 9;q++) { int k = i * pow(10,6) + j * pow(10,5) + p * pow(10,4) + q * pow(10,3) + p * pow(10,2) + j * pow(10,1) + i * pow(10,0); if(k > b || k < a) continue; if(test2(k)) printf("%d\n",k); } } } int main() { freopen("pprime.in","r",stdin); freopen("pprime.out","w",stdout); for(int i = 1;i <= 10000;i++) if(test(i)) { pri[i]=1; prinum[ans++]=i; } scanf("%d%d",&a,&b); pal(); return 0; }