usaco - 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

写了好久最后看了提示才写出来......

这道题需要注意的地方:

1.求素数的时候只需要从2一直判断到n的开方就行了(如果这个有大于根号n的因子,那么另一个因子一定小于根号n)
2.偶数位数的回文一定能被11整除,因此只需要生成奇数位数的回文即可(11要特殊判断)

/*
ID:
PROG: pprime
LANG: C++
*/
#include<cstdio>
int a,b;
int tem;
int prime(int n){
    for(int i=2;i*i<=n;i++){
        if(n%i==0)return 0;
    }
    return 1;
}
int main(){
    freopen("pprime.in","r",stdin);
    freopen("pprime.out","w",stdout);
    scanf("%d%d",&a,&b);
    //5-11的即使素数又的回文数(12-99中是回文的数不是素数)
    for(int i=5;i<=11;i++){
        if(prime(i)&&i>=a&&i<=b)printf("%d\n",i);
    }
    for(int i1=0;i1<=9;i1++)
        for(int i2=0;i2<=9;i2++)
        for(int i3=0;i3<=9;i3++)
        for(int i4=0;i4<=9;i4++)
        for(int i5=0;i5<=9;i5++){
            if(!i1&&!i2&&!i3)tem=101*i4+10*i5;//3位
            else if(!i1&&!i2)tem=10001*i3+1010*i4+100*i5;//5位
            else if(!i1)tem=1000001*i2+100010*i3+10100*i4+1000*i5;//7位
            if(prime(tem)&&tem>=a&&tem<=b)printf("%d\n",tem);
        }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值