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
题意:输入区间[a,b]求区间中的即是回文数又是素数的数。
分析:打出全部的回文数表,打出sqrt(b)中的素数表,然后再依次判断。
View Code
1 /* 2 ID: dizzy_l1 3 LANG: C++ 4 TASK: pprime 5 */ 6 #include<iostream> 7 #include<algorithm> 8 #include<cstdio> 9 #include<cmath> 10 #include<stdlib.h> 11 #include<cstring> 12 13 using namespace std; 14 15 int palind[20000],prime[10000],cnt1,cnt2; 16 bool flag,isprime[10000]; 17 18 void dfs(int p,int n,char *s) 19 { 20 if(p>n) return ; 21 if(p==n) 22 { 23 int q,i,k; 24 char ts[10]; 25 for(i=0;i<10;i++) 26 ts[i]=s[i]; 27 if(flag) q=p; 28 else q=p-1; 29 k=p+1; 30 for(i=q;i>=1;i--) 31 ts[k++]=s[i]; 32 palind[cnt1++]=atoi(ts); 33 return ; 34 } 35 char c; 36 for(c='0';c<='9';c++) 37 { 38 s[p+1]=c; 39 dfs(p+1,n,s); 40 } 41 } 42 43 void Init_palind(int n) 44 { 45 int i,j; 46 char s[10],c; 47 cnt1=0; 48 if(n==9) n--; 49 for(i=1;i<=n;i++) 50 { 51 memset(s,'\0',sizeof(s));s[0]='0'; 52 if(i&1) flag=false; 53 else flag=true; 54 j=(i+1)/2; 55 for(c='1';c<='9';c++) 56 { 57 if(i==1) 58 { 59 palind[cnt1++]=c-'0'; 60 } 61 else 62 { 63 s[1]=c; 64 dfs(1,j,s); 65 } 66 } 67 } 68 // for(i=0;i<cnt1;i++) 69 // printf("%d ",palind[i]); 70 } 71 72 void Init_prime(int n) 73 { 74 int i,j,m; 75 cnt2=0; 76 m=sqrt(n); 77 memset(isprime,true,sizeof(isprime)); 78 isprime[1]=false; 79 for(i=2;i<=m;i++) 80 { 81 if(isprime[i]) 82 { 83 prime[cnt2++]=i; 84 for(j=i+i;j<=m;j=j+i) 85 { 86 isprime[j]=false; 87 } 88 } 89 } 90 // for(i=0;i<cnt2;i++) 91 // printf("%d ",prime[i]); 92 } 93 94 bool judge(int n) 95 { 96 int i; 97 for(i=0;i<cnt2&&prime[i]*prime[i]<=n;i++) 98 { 99 if(n%prime[i]==0) 100 return false; 101 } 102 return true; 103 } 104 105 void work(int a,int b) 106 { 107 int i,j,k; 108 i=0;j=cnt1-1; 109 while(palind[i]<a) i++; 110 while(palind[j]>b) j--; 111 for(k=i;k<=j;k++) 112 { 113 if(judge(palind[k])) 114 { 115 printf("%d\n",palind[k]); 116 } 117 } 118 } 119 120 int main() 121 { 122 freopen("pprime.in","r",stdin); 123 freopen("pprime.out","w",stdout); 124 int a,b; 125 char ca[15],cb[15]; 126 while(scanf("%s %s",ca,cb)==2) 127 { 128 a=atoi(ca); 129 b=atoi(cb); 130 Init_palind(strlen(cb)); 131 Init_prime(b); 132 work(a,b); 133 } 134 return 0; 135 }