USACO-cha1-sec1.5 Prime Palindromes

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)

5
7
11
101
131
151
181
191
313
353
373

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) {//odd
		for(int k = 0; k < len; k++)
			从中间向两边复制;
		a[len*2-1] = '\0';
    }
    else {
        ......
    }
    a转换成数字b;
    return b;
}

代码如下:

/*
ID: j.sure.1
PROG: pprime
LANG: 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) {//odd
		for(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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值