HOJ 1004 ACM刷题记录

最近开始在哈工大的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 .

Input

Line 1: Two integers, a and b

Output

The list of palindromic primes in numerical order, one per line.

Sample Input
5 500
Sample 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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值