SOJ 4190. Prime Palindromes solution

来源:互联网 发布:北京大数据培训班 编辑:程序博客网 时间:2024/06/05 20:34

链接:

http://soj.sysu.edu.cn/4190

大意:在[5,100000000]的范围内找出一个给定区间所有即是回文数又是素数的数

4190. Prime Palindromes

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

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

5 5000 0

Sample Output

5711101131151181191313353373383

思路有两个方向

1.找出范围内素数,判断是否为回文数

2.找出范围内回文数,判断是否为素数

我采用第二种方法

#include <cstdio>#include <algorithm>#include <string>#include <stack>#include <cstring>#include <vector>//参考了一个博客的生成回文数的方法//链接http://www.cnblogs.com/chenyg32/p/3277613.html//预先打素数表加速判断一个回文数是否为素数//采用欧拉筛法打表//偶数位的回文数是11的倍数,所以只考虑奇数位的回文数和11using namespace std;int main() {    int a, b;    bool NotPrime[10001] = { 0 };    int primes[1240];    NotPrime[0] = NotPrime[1] = true;    int point = 0;    //打素数表    //欧拉筛法    for (int i = 2; i < 10001; ++i) {        if (NotPrime[i] == false)            primes[point++] = i;        for (int j = 0; j < point && i * primes[j] < 10001; ++j) {            NotPrime[i*primes[j]] = true;            if (i%primes[j] == 0)                break;        }    }    //回文数表    //生成部分参照那份博客    //生成回文数后试除判断是否为素数    //觉得试除效率低的同学也可以试一试看能不能打表打到1千万,因为大于等于1千万的回文数是偶数位,一定不是素数    vector <int > v;    v.push_back(11);    for (int i = 2; i < 10001; ++i) {        int tmp = i / 10, sum;        for (sum = i; tmp != 0; tmp /= 10) {            sum = sum * 10 + tmp % 10;        }        bool isPrime = true;        int tem = sqrt(sum);        for (int j = 0; j < point && primes[j] <= tem; ++j) {            if (sum % primes[j] == 0) {                isPrime = false;                break;            }        }        if (isPrime)            v.push_back(sum);    }    sort(v.begin(), v.end());    while (scanf("%d%d", &a, &b) && a && b) {        if (b < a)            swap(a, b);        for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) {            if (*it < a)                continue;            else if (*it > b)                break;            printf("%d\n",*it);        }    }    return 0;}


原创粉丝点击