您的位置:首页 > 其它

一亿以内的回文素数

2015-08-30 21:29 183 查看
题意分析:求给定区间内的质数回文数
题目分析:
1.多组测试数据,所以先打表。
2.先求质数再判断回文,效率低下;所以先构造回文数,再判断质数。
3.偶数位的回文数都能被11整除,自己证明去。所以,偶数位的回文数除了11都是合数。
4.一个k位数,可以构造出一个奇数位的回文数。比如13,可以构造131;189可以构造18981.所以100000000内的只要从1构造到9999即可。
5.若范围为1000000000,那么明显超出int范围,要用long long。当然此题无此陷阱。
6. 最后按从小到大的顺序输出,优先队列搞定。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <cmath>
#include <vector>
#define MAXN 10000
#define RST(N)memset(N, 0, sizeof(N))
using namespace std;

typedef long long LL;

struct cmp
{
    bool operator()(const int &a, const int &b)
    {
        return a > b;
    }
};

priority_queue <int, vector<int>, cmp> pq;

bool is_prime(int x)
{
    for(int i=2; i<sqrt(x+0.5); i++) {
        if(x % i == 0) return false;
    }
    return true;
}

int main()
{
    //freopen("data.in", "r", stdin);
    //freopen("data.out", "w", stdout);
    while(!pq.empty()) pq.pop();
    pq.push(11);
    int sum, tmp;
    for(int i=2; i<MAXN; i++) {
        for(sum=i, tmp=i/10; tmp!=0; tmp/=10) {
            sum = sum*10 + tmp%10;
        }
        if(is_prime(sum)) pq.push(sum);
    }
    while(!pq.empty()) {
        cout << pq.top() << endl;
        pq.pop();
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: