码迷,mamicode.com
首页 > 其他好文 > 详细

回文质数 USACO

时间:2017-02-04 14:32:13      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:ted   algo   scanf   icon   ret   style   anim   usaco   ide   

时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold
题目描述 Description

因为 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数.
写一个程序来找出范围[a,b](5<=a<b<=100,000,000)间的所有回文质数;

因为 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 是回文质数.写一个程序来找出范围[a,b](5<=a<b<=100,000,000)间的所有回文质数;

输入描述 Input Description

*Line 1: a,b

输出描述 Output Description

a与b之间(含)的所有回文质数

一行一个

样例输入 Sample Input

5 500

样例输出 Sample Output

5
7
11
101
131
151
181
191
313
353
373
383

先找回文数,再判断是不是质数。

代碼實現(codevs 38ms,洛谷 44ms):

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 int a,b,c,s;
 5 int hw[300000];
 6 void find(int x){
 7     c=s=x;c/=10;
 8     while(c){s*=10;s+=c%10;c/=10;}
 9     if(s>b) return;
10     if(s>=a) hw[++hw[0]]=s;
11     c=s=x;
12     while(c){s*=10;s+=c%10;c/=10;}
13     if(s>b) return;
14     if(s>=a) hw[++hw[0]]=s;
15     for(int i=0;i<10;i++) find(10*x+i);
16 }
17 int main(){
18     scanf("%d%d",&a,&b);
19     for(int i=1;i<=9;i+=2){
20         s=i;
21         find(i);
22     }
23     sort(hw+1,hw+hw[0]+1);
24     for(int i=1;i<=hw[0];i++)
25     for(int j=2;j*j<=hw[i];){
26         if(hw[i]%j==0) break;
27         j++;
28         if(j*j>hw[i]) printf("%d\n",hw[i]);
29     }
30     return 0;
31 }

 

应老师要求,稍微优化了一下(codevs 4ms):

 

题目来源

回文质数 USACO

标签:ted   algo   scanf   icon   ret   style   anim   usaco   ide   

原文地址:http://www.cnblogs.com/J-william/p/6160855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!