Prime Palindromes 回文质数(暴力构造)

Description

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

Input

第 1 行: 二个整数 a 和 b

Output

输出一个回文质数的列表,一行一个。

Sample Input

5 500

Sample Output

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

题解:

直接暴力肯定会T,那就间接暴力呗。先找出从 a 到 b 之间的回文数,再在这些回文数里边找素数。

因为有些地方没处理好,所以在 b < 99999 的时候直接就暴力找回文数了......

代码如下:  string  函数的用法

#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long LL;
int h[51111];
int str_int(string t)             //string 转 int
{
    int ans;
    istringstream is(t);
    is >> ans;
    return ans;
}

void int_str(int i,string &s)    //int 转 string
{
    ostringstream os;
    os << i;
    s+=os.str();
}
int main()
{
    int a,b,p=0,L;
    string k;
    cin >> a >> b;
    if(b<99999)
        L=b;
    else
    {
        int m=sqrt(b+1),ll=1;
        int_str(m,k);
        for(int i=1; i<k.size(); i++)
            ll*=10;
        L=ll*(k[0]-'0'+1);
    }

    for(int i=1; i<=L; i++)
    {
        string t,s;
        int_str(i,s);
        t+=s;
        int len=s.size();
        reverse(s.begin(),s.end());
        t+=s;
        if(str_int(t)<=b&&str_int(t)>=a)
            h[p++]=str_int(t);
        for(char j='0'; j<='9'; j++)
        {
            t.erase(len);                         //删到从下标为len至结尾的字符 
            t+=j;
            t+=s;
            if(str_int(t)<=b&&str_int(t)>=a)
                h[p++]=str_int(t);
        }
        if(i<10&&i>=a)
            h[p++]=i;

    }
    sort(h,h+p);
    int j;
    for(int i=0; i<p; i++)
    {
        int m=sqrt(h[i])+1;
        for(j=2; j<=m; j++)
        {
            if(h[i]%j==0)
                break;
        }
        if(j>m)
            cout << h[i] <<endl;
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值