USACO SECTION 1.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

 

Test 1: TEST OK [0.000 secs, 2340 KB]  

Test 2: TEST OK [0.000 secs, 2340 KB]  

Test 3: TEST OK [0.032 secs, 2340 KB]  

Test 4: TEST OK [0.032 secs, 2340 KB]  

Test 5: TEST OK [0.032 secs, 2340 KB]  

Test 6: TEST OK [0.032 secs, 2340 KB]  

Test 7: TEST OK [0.043 secs, 2340 KB]  

Test 8: TEST OK [0.032 secs, 2340 KB]  

Test 9: TEST OK [0.832 secs, 2340 KB]

 

/*
ID: conicoc1
LANG: C
TASK: pprime
*/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int A[9]={
		1,10,100,1000,10000,100000,1000000,10000000,100000000
	};
int Answer[10000];
int k=0;
int a,b;
int Length;

int count=0;

int IsPrime(int Number)
{
	int i;
	double TempNumber;
	TempNumber=(double)Number;
	if(Number%2==0)
		return 0;
	for(i=3;i<=sqrt(TempNumber);i+=2)
	{
		if(Number%i==0)
			return 0;
	}
	return 1;		
}

void FindPalindromes(int Sum,int Length,int N)  //长度为Length回文的第N位 
{
	int i;
	int temp;
//	printf("%d\n",count++);
	if(N>Length/2)   //说明是递归的最后一次 
	{
		for(i=0;i<=9;i++)
		{
			if(Length%2==0)  //如果是偶数
			{
				temp=Sum+i*A[N-1]+i*A[Length-N];
				if(IsPrime(temp)&&temp>=a&&temp<=b)
					Answer[k++]=temp;		
			}
			else
			{
				temp=Sum+i*A[N-1];
				if(IsPrime(temp)&&temp>=a&&temp<=b)
					Answer[k++]=temp;
			}
		} 
	}
	else
	if(N==1)
	{
		for(i=1;i<=9;i+=2)
		{
			FindPalindromes(Sum+i*A[Length-1]+i*A[N-1],Length,N+1);
		}
	}
	else
	{
		for(i=0;i<=9;i++)
		{
			FindPalindromes(Sum+i*A[N-1]+i*A[Length-N],Length,N+1);
		}
	}
	
}

int main()
{
	FILE *fin,*fout;
	fin=fopen("pprime.in","r");
	fout=fopen("pprime.out","w");

	fscanf(fin,"%d %d",&a,&b);
	
	int Length=0;
	int temp=b;
	
	while(temp!=0)
	{
		Length++;
		temp/=10;
	}
	
	for(count=1;count<=Length;count++)	
		FindPalindromes(0,count,1);  //长度为Length回文的第N位
	
	for(count=0;count<k;count++)
		fprintf(fout,"%d\n",Answer[count]);
		
	return 0;
}


 

一开始用爆搜果断跪了,所以先找回文。

用深搜,打印出来直接是有序的,应该还可以减枝

貌似判断素数还可以优化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值