最近开始在哈工大的HOJ上刷了一些题目,是时候该整理一下了,所以在博客上记录一下
从头开始吧,从我最早做的一道比较有难度的题目开始吧,就是回文素数。HOJ 1004
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
以上是题目:给出一个范围,打印出范围内所有回文素数。
有一点需要注意:挨个判断理论上可以,但会超时。所以我想到的方法是构造回文数,然后判断是否是素数。
回文数有两类:偶数位数与奇数位数,偶数位数的回文数都可以整除11,所以只需要构造奇数位数的回文数。代码时间长了,文件丢了,重新去HOJ上粘的,代码如下:
#include <stdio.h> #include <math.h> int make(int x);/*构造回文数*/ int sushu(int x);/*检验素数*/ main() { int a,b,sum,i; scanf("%d%d",&a,&b); if(5>=a && 5<=b) printf("5\n"); if(7>=a && 7<=b) printf("7\n"); if(11>=a && 11<=b) printf("11\n"); i=10; sum=make(10); while (sum<=b) { if(sushu(sum)) printf("%d\n",sum); i++; sum=make(i); } return 0; } int make(int x) { int s; s=x; x=s/10; while(x>0) { s=s*10+x%10; x=x/10; } return s; } int sushu(int x) { int i,s; s=(int)sqrt(x); for(i=2;i<=s;i++) { if(x%i==0) return 0; } return 1; }