Prime Palindromes
Prime Palindromes
Source : USACO
Gateway Time
limit : 15 sec Memory
limit : 32 M
Submitted : 20750, Accepted : 4606
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 <= 1000,000,000); both a and b are considered to be within the range .
InputLine 1: Two integers, a and b
OutputThe list of palindromic primes in numerical order, one per line.
Sample Input5 500
Sample Output5
7
11
101
131
151
181
191
313
353
373
383
*This Code is Submitted by aprilvkuo for Problem 1004 at 2012-10-21 19:25:17*/
#include <stdio.h>
#include <math.h>
int prime(long int w)//判断一个数是不是素数
{
long i;
if(w%2)
{
for(i=3; i<=sqrt(w); i+=2)
{
if(w%i==0)
return 0;
}
return 1;
}
else
return 0;
}
int main()
{
int a=0,b=0,c=0,d=0,e=5;//构造回文,将每个数看错由9个数字组成的,关于第五个数字对称,首位可为0,a-e为其前5位,从数字5开始判断
long int w,m,n;//w存放着构造的回文
scanf("%ld%ld",&m,&n);
while (a<=9) //第五位数字递加,由小到大构造回文数
{
if (e==10)
{
e=0;
d++;
}
if (d==10)
{
d=0;
c++;
}
if (c==10)
{
c=0;
b++;
}
if (b==10)
{
b=0;
a++;
}
w=a*100000000+b*10000000+c*1000000+d*100000+e*10000+d*1000+c*100+b*10+a;//从小到大开始构造回文w
while (w%10==0) //将那些9位数字最前面有0的数最后面的0对应去除,化为回文数
{
w=w/10;
}
if(w==5)//因为后面剔除了5,要先判断是不是5,是否输出5
printf("5\n");
if( w >= m && w <=n ) //判断构造的回文是否在给定的范围内
{
if((w%2)&&((w%5!=0)&&((2*(a+b+c+d)+e)%3!=0)))//剔除掉尾数为5,2,4,6,8的非素数回文
{
if (prime(w))//判断范围内的回文是不是素数
{
printf("%ld\n",w);
if ((w==7)&&(n>=11))//由提示可知,11为唯一一个为素数的偶数位数,所以在最后一个一位数回文素数输出后,第一个三位数回文素数输出前,要输出11
printf("11\n");
}
}
}
e++;
}
return 0;
}
Prime Palindromes
Source : USACO Gateway | |||
Time limit : 15 sec | Memory limit : 32 M |
Submitted : 20750, Accepted : 4606
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 <= 1000,000,000); both a and b are considered to be within the range .
InputLine 1: Two integers, a and b
OutputThe list of palindromic primes in numerical order, one per line.
Sample Input5 500Sample Output
5 7 11 101 131 151 181 191 313 353 373 383
输入: a,b
输出:输出a,b之间所有的回文素数。
首先,先明确回文数和素数的定义。
回文数:左右对称的数,比如123321,12321。
素数:只能被1和自身整除的数。如2,3,5,7……
判断回文数有两种方案:
1.先得到素数,再判断是不是回文数。
2.先得到回文数,再判断是不是素数。
方案一:素数数目过多,如果先得到素数再回文,可能超出时间限定。
方案二:先找出回文数再判断是不是素数。最大的范围为0—1000,000,000。
有一些数学性质可知:1. 11是唯一的偶数位回文素数
2. 以2,4,6,8,0,5结尾的数必是偶数,可以排除
所以,可以用一个5位数来构造,还可以排除这个五位数的6/10的数,需要判断的数目为99999*0.6,大概6万个。
有待完善