Prime Palindromes

Prime Palindromes

Time Limit: 1sec Memory Limit:256MB
Description
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 .
Input
There are multiple test cases.
Each case contains two integers, a and b.
a=b=0 indicates the end of input.
Output
For each test case, output the list of palindromic primes in numerical order, one per line.

Sample Input
Copy sample input to clipboard
5 500
0 0
Sample Output
5
7
11
101
131
151
181
191
313
353
373
383

题意:给出两个整数a和b (5 <= a < b <= 100,000,000),求a和b 之间所有的回文素数。
思路:刚看到题目的时候,没考虑空间和时间限制问题,没觉得难,思路是先判断素数,后判断回文数来筛选。但是一提交,很悲剧地超时了!
          在网上查了些资料,方法很多,比较有效的是先筛回文数(回文数比较少),再判断素数。K位的整数可以生成2*K或者2*K-1位的回文数,比如说123,可以生成回文数123321或者12321,对于100,000,000以内的回文数,100,000,000不是回文数可以排除,剩下的最大数是99,999,999,8个九,只需要4位就可以构造了。求出所以的回文数之后,加一个素数判断,将回文素数存进一个数组里。最后找出a和b之间的回文素数即可。 

出现一件很诡异的事,将代码中的#include<set>和set<int> s两个语句删除之后竟然是WA!!不删的话就能AC。OTL。。。哪位大神能帮我找找是什么原因==

        想了解更多 可以参考以下网址:  http://zrj.me/archives/506 

代码如下:
#include<iostream>
#include<set>
#include<algorithm>
using namespace std;

long a,b;
set<int> s;
long f[15000];

bool isprime(long x)
{
     for(int i=2;i*i<=x;i++)
     {
             if(x%i==0)return 0;
              
     } 
     return 1;
 }
 
void palindrome()
{
     int cnt=0;
     for(int i=1;i<10000;i++)
     {
             long num=i,re;
             for(re=i;num!=0;num/=10)
             {
                 re=re*10+num%10;
             }
             if(isprime(re)){f[cnt]=re;cnt++;}
     
             num=i/10;
             
             for(re=i;num!=0;num/=10)
             {
                 re=re*10+num%10;
             }
             if(isprime(re)){f[cnt]=re;cnt++;}
     }
     sort(f,f+cnt);
 }
 
int main()
{
    palindrome();
    while(cin>>a>>b&&a&&b)
    {
        
        for(int i=0;f[i]<=b;i++)
        {
                if(f[i]>=a)cout<<(int)f[i]<<endl;
        }
       
    }
    
    return 0;
}                                 



         
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值