素数回文(小技巧)

https://cn.vjudge.net/problem/HDU-1431

xiaoou33对既是素数又是回文的数特别感兴趣。比如说151既是素数又是个回文。现在xiaoou333想要你帮助他找出某个范围内的素数回文数,请你写个程序找出 a 跟b 之间满足条件的数。(5 <= a < b <= 100,000,000); 

Input

这里有许多组数据,每组包括两组数据a跟b。

Output

对每一组数据,按从小到大输出a,b之间所有满足条件的素数回文数(包括a跟b)每组数据之后空一行。

Sample Input

5 500

Sample Output

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

这个题其实是一个水题,

注意两点:一般的暴力做法一定超时, 输出是从小到大;

解题思路:因为不能暴力;所以有一定的小技巧。

题目给的是1e8的范围;遍历一定超时,如果我们遍历1到10000,求出相应的回文然后判断是不是素数,将其保存在数组中,

可以达到同样的效果。

输出时题目有要求。从小到大!!!!

#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>

using namespace std;
int s[100000000+100];

int prime(int x)//判断是否是素数。
{
    int i;
    for(i=2; i<=sqrt(x); i++)
        if(x%i==0)
            return 0;
    return 1;
}

int huiwen(int x)//判断是否为回文。
{
    int a[20];
    int top=0, i;
    int n = x;
    while(n)
    {
        a[top++] = n%10;
        n = n/10;
    }
    int mid = (top-1)/2;
    for(i=0; i<=mid; i++)
    {
        if(a[i]!=a[top-1-i])
            return 0;
    }
    return 1;
}

int bhw(int x)//构造回文。
{
    int a[20];
    int top=0, i;
    int n = x;
    while(n)
    {
        a[top++] = n%10;
        n = n/10;
    }
    int sum = 0;
    for(i=top-1; i>=0; i--)
    {
        sum = sum * 10 + a[i];
    }
    for(i=1; i<=top-1; i++)
    {
        sum = sum * 10 + a[i];
    }
    return sum;
}
int main()
{
    int a, b, i, top=0;
    for(i=5; i<=10000; i++)
    {
        if(prime(i)==1 && huiwen(i)==1)
        {
            s[top++] = i;
        }
        int y = bhw(i);
        if(y<=10000) continue;
        if(prime(y)==1)
            s[top++] = y;
    }
    sort(s, s+top);
    while(~scanf("%d%d", &a, &b))
    {
        for(i=0; i<top; i++)
        {
            if(s[i]>=a && s[i]<=b)
                printf("%d\n", s[i]);
            if(s[i]>b)
                break;
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/82377650