[搜索]USACO-1.5-Prime Palindromes

来源:互联网 发布:java 什么意思 编辑:程序博客网 时间:2024/05/05 23:16

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
1
1101
151
131181
353
191313373
383

给定一个范围,输出在这个范围内(包含边界)的所有回文素数.
注意以后有回文数的情况,尽量先用DFS生成回文数表,然后在做处理,不要去枚举产生回文数.
这里打出回文数表以后先排序,然后二分查出上下界,把该范围中的所有素数输出即可。

代码:
/*ID:yfr_1992PROG:pprimeLANG:C++*/#include<iostream>#include<cstdio>#include<cstring>#include<vector>#include<cstdlib>#include<algorithm>#include<cmath>using namespace std;vector<int> plist;int temp[10],sz;void dfs(int cur,int limit){    if(cur>((limit-1)>>1)){        int sum = 0;        for(int i=0;i<limit;i++)sum = sum*10 + temp[i];        plist.push_back(sum);        return;    }    for(int i=0;i<10;i++){        temp[cur] = i,temp[limit-1-cur] = i;        dfs(cur+1,limit);    }}bool isPrime(int x){    for(int i=2;i<=(int)sqrt(x)+1;i++){        if((x%i)==0)return false;    }    return true;}int bs_lower(int x){    int l = 0, r = sz-1 , m ;    while(l<=r){        m = (l+r)>>1;        if(plist[m]>=x)r = m-1;        else l = m+1;    }    return l;}int bs_upper(int x){    int l = 0, r = sz-1 , m ;    while(l<=r){        m = (l+r)>>1;        if(plist[m]>x)r = m-1;        else l = m+1;    }    return r;}int main(){    freopen("pprime.in","r",stdin);    freopen("pprime.out","w",stdout);    for(int i=1;i<=8;i++)dfs(0,i);    sort(plist.begin(),plist.end());    sz = 1;    for(int i=1;i<(int)plist.size();i++){        if(plist[i]!=plist[i-1])plist[sz++] = plist[i];    }    int a,b;    scanf("%d%d",&a,&b);    int s = bs_lower(a), e = bs_upper(b);    for(int i=s;i<=e;i++){        if(isPrime(plist[i]))printf("%d\n",plist[i]);    }    return 0;}


原创粉丝点击