题目:
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
这是非常纠结的一道题目。一开始的算法老超时,才返现原来将数字转化为string的时候用了sstream函数库函数会非常的慢,于是参照别人的办法用了下面的代码。结果还是一直超时,原本见题目有一亿的数于是开了long long,结果尝试一下改为int之后竟然过了!被坑的无语!
题目思路还是非常清晰的,先用筛选法求素数打出在范围内的素数表,再对其中的素数判断是否是回文数,将是的存进一个数组中方便最后的查找输出。
题目有几点要注意的地方:
1.由于数组比较大所以要声明在main函数的外面,否则会很容易爆栈。
2.这里涉及到筛选法求素数,参考 http://blog.sina.com.cn/s/blog_69c62b650100y53r.html
3.memset函数的使用。
1 #include2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 8 #define MAX 10000000//比题目要求少一个0即可,加多一个0则内存溢出老是RE! 9 bool prime[MAX+1]; //prime[i]=true表示i为素数10 int PrimePalindromeList[100000]={ 0};11 12 void createPrimeList();13 bool isPalindrome(int n);14 void createPrimePalindromeList();15 16 int main(){17 createPrimeList();18 createPrimePalindromeList();19 int a,b;20 scanf("%d %d",&a,&b);21 while(!(a==0&&b==0)){22 int i=0;23 while(PrimePalindromeList[i]
附:筛选法求素数步骤
1.开一个大的bool型数组prime[],大小就是n+1就可以了.先把所有的下标为奇数的标为true,下标为偶数的标为false.
2.然后: for( i=3; i<=sqrt(n); i+=2 ) { if(prime[]) for( j=i+i; j<=n; j+=i )prime[j]=false; }3.最后输出bool数组中的值为true的单元的下标,就是所求的n以内的素数了。原理很简单,就是当i是质(素)数的时候,i的所有的倍数必然是合数。如果i已经被判断不是质数了,那么再找到i后面的质数来把这个质 数的倍数筛掉。 一个简单的筛素数的过程:n=30。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 第 1 步过后2 4 ... 28 30这15个单元被标成false,其余为true。 第 2 步开始: i=3; 由于prime[3]=true, 把prime[6], [9], [12], [15], [18], [21], [24], [27], [30]标为false. i=4; 由于prime[4]=false,不在继续筛法步骤。 i=5; 由于prime[5]=true, 把prime[10],[15],[20],[25],[30]标为false. i=6>sqrt(30)算法结束。 第 3 步把prime[]值为true的下标输出来: for(i=2; i<=30; i++) if(prime) printf("%d ",i); 结果是 2 3 5 7 11 13 17 19 23 29