首页 > 代码库 > Prime Palindromes

Prime Palindromes

链接

分析:暴力枚举1-8位数,并判断是否为素数

技术分享
 1 /*
 2     PROB:pprime
 3     ID:wanghan
 4     LANG:C++
 5 */
 6 #include "iostream"
 7 #include "cstdio"
 8 #include "cstring"
 9 #include "string"
10 #include "vector"
11 #include "algorithm"
12 using namespace std;
13 vector<int> h;
14 int a,b;
15 bool judge(int x){
16     if(x<=2)
17         return false;
18     for(int i=2;i*i<=x;i++)
19         if(x%i==0)
20             return false;
21     return true;
22 }
23 void solve12(){     //1 2
24     for(int i=0;i<=9;i++){
25         int num1=i;
26         int num2=i*10+i;
27         if(judge(num1))  h.push_back(num1);
28         if(judge(num2))  h.push_back(num2);
29     }
30 }
31 void solve34(){   //3 4
32     for(int i=0;i<=9;i++){
33         for(int j=0;j<=9;j++){
34             int num3=100*i+10*j+i;
35             int num4=1000*i+100*j+10*j+i;
36             if(judge(num3))  h.push_back(num3);
37             if(judge(num4))  h.push_back(num4);
38         }
39     }
40 }
41 void solve56(){  //7 8
42     for(int i=0;i<=9;i++){
43         for(int j=0;j<=9;j++){
44             for(int k=0;k<=9;k++){
45                 int num5=10000*i+1000*j+100*k+10*j+i;
46                 int num6=100000*i+10000*j+1000*k+100*k+10*j+i;
47                 if(judge(num5))  h.push_back(num5);
48                 if(judge(num6))  h.push_back(num6);
49             }
50         }
51     }
52 }
53 void solve78(){
54     for(int i=0;i<=9;i++){
55         for(int j=0;j<=9;j++){
56             for(int k=0;k<=9;k++){
57                 for(int f=0;f<=9;f++){
58                     int num7=1000000*i+100000*j+10000*k+1000*f+100*k+10*j+i;
59                     int num8=10000000*i+1000000*j+100000*k+10000*f+1000*f+100*k+10*j+i;
60                     if(judge(num7))  h.push_back(num7);
61                     if(judge(num8))  h.push_back(num8);
62                 }
63             }
64         }
65     }
66 }
67 int main()
68 {
69     freopen("pprime.in","r",stdin);
70     freopen("pprime.out","w",stdout);
71     cin>>a>>b;
72     solve12(); solve34();solve56();solve78();
73     sort(h.begin(),h.end());
74     int len=h.size();
75     for(int i=0;i<len;i++){
76         if(h[i]>=a&&h[i]<=b)
77             cout<<h[i]<<endl;
78     }
79     return 0;
80 }
View Code

 

Prime Palindromes