USACO-cha1-sec1.5 Prime Palindromes

来源:互联网 发布:适合妈妈穿的淘宝店 编辑:程序博客网 时间:2024/06/14 15:48

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)

5711101131151181191313353373

383

————————————————————奇怪的分割线————————————————————

前言:回文数整死我了,终于知道怎么生成回文数了。折半枚举就好了。

思路:先看如何生成回文数

因为数据范围是100000000以内的回文数,所以只需要枚举1~9999,之后将其输出到字符串,根据奇偶性分类反转,再输入到数字就行了。折半枚举:

for(int i = 1; i <= 9999; i++) {    for(int oe = 0; oe < 2; oe++) {//奇偶交替        x = palindrome(i, oe);        if(x合法且为素数)            记录x;    }}
翻转:

int palindrome(int i, int oe){char a[];int b;i转换成字符串a;int len = strlen(a);    if(oe == 1) {//oddfor(int k = 0; k < len; k++)从中间向两边复制;a[len*2-1] = '\0';    }    else {        ......    }    a转换成数字b;    return b;}

代码如下:

/*ID: j.sure.1PROG: pprimeLANG: C++*//****************************************/#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <queue>#include <vector>#include <map>#include <string>#include <iostream>using namespace std;/****************************************/int A, B;int answer[100000];bool prime(int a){if(a == 1)return false;for(int i = 2; i*i <= a;i++)if(a % i == 0)return false;return true;}int palindrome(int i, int parity){char a[30];int b;sprintf(a, "%d", i);int len = strlen(a);    if(parity == 1) {//oddfor(int k = 0; k < len; k++)a[k+len-1] = a[len-k-1];a[len*2-1] = '\0';    }    else {        for(int k = 0; k < len; k++)a[k+len] = a[len-k-1];        a[len*2] = '\0';    }    sscanf(a, "%d", &b);    return b;}int main() {freopen("pprime.in", "r", stdin);freopen("pprime.out", "w", stdout);scanf("%d%d", &A, &B);int x;int n = 0;for(int i = 1; i <= 9999; i++) {for(int j = 0; j < 2; j++) {x = palindrome(i, j);if(x >= A && x <= B && prime(x)) {answer[n++] = x;}}if(x > B)break;}sort(answer, answer+n);for(int i = 0; i < n; i++)printf("%d\n",answer[i]);fclose(stdin);fclose(stdout);return 0;}



0 0
原创粉丝点击