洛谷P1217回文质数(特判筛选,取巧判断顺序)

题目链接:https://www.luogu.org/problemnew/show/P1217#sub

分析和思路:

最有解法是制造回文数,一个一个判断的话一般是会超时的,但如果各种取巧+优化的话也能过。

其中,取巧务必注意:

回文判断必须放在前面能过!要是把素数判断放前面(可能是素数太多吧起码比回文多)任你再怎么优化也必然必T

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 int prime(int x)
 6 {
 7     if(x<=1) return 0;
 8     else if(x==2 || x==3) return 1;
 9     else
10     {
11         if(x%2==0) return 0;
12         for(int i=2;i*i<=x;i++)
13         {
14             if(x%i==0) return 0;
15         }
16         return 1;
17     }
18 }
19 
20 int solve(int x)
21 {
22     int a=x,b=0;
23     while(x)
24     {
25         b=b*10+x%10;
26         x/=10;
27     }
28     
29     if(a==b) return 1;
30     else return 0;
31 }
32 
33 
34 int main()
35 {
36     ios::sync_with_stdio(false); cin.tie(0); 
37     int a,b;
38     cin>>a>>b;
39     
40     if(a%2==0)
41     {
42         a++;
43     }
44     if(b>9989899)
45     {
46         b=9989899;
47     }
48     for(int i=a;i<=b;i+=2)
49     {
50         if(solve(i) && prime(i))
51         {
52             cout<<i<<endl; 
53         }
54     }
55     
56     return 0;
57 } 

完。

原文地址:https://www.cnblogs.com/redblackk/p/9609557.html