码迷,mamicode.com
首页 > 其他好文 > 详细

【USACO】Prime Palindromes(暴力暴力再暴力)

时间:2015-04-14 21:34:36      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

把所有符合条件的数全部记下来,扫一遍就行了,这类数最多2W来个

/*
ID: 18906421
LANG: C++
PROG: pprime
*/
#include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 20005;
int a,b;
int cnt = 0;
int prime[maxn];
bool is_prime(int v){
    int e = sqrt(v) + 1;
    for(int i = 2; i <= e; i++)
        if(v % i == 0) return false;
    return true;
}
int solve1(){ //1 2
    for(int i = 1; i <= 9; i++){
        int v1 = i;
        int v2 = i * 10 + i;
        if(is_prime(v1)) prime[cnt++] = v1;
        if(is_prime(v2)) prime[cnt++] = v2;
    }
}
int solve2(){//3 4
    for(int i = 1; i <= 9; i++){
        for(int j = 0; j <= 9; j++){
            int v1 = i * 100  + j * 10  + i;
            int v2 = i * 1000 + j * 100 + j * 10 + i;
            if(is_prime(v1)) prime[cnt++] = v1;
            if(is_prime(v2)) prime[cnt++] = v2;
        }
    }
}
int solve3(){//5 6
    for(int i = 1; i <= 9; i++){
        for(int j = 0; j <= 9; j++){
            for(int k = 0; k <= 9; k++){
                int v1 = i * 10000  + j * 1000  + k * 100  + j * 10  + i;
                int v2 = i * 100000 + j * 10000 + k * 1000 + k * 100 + j * 10 + i;
                if(is_prime(v1)) prime[cnt++] = v1;
                if(is_prime(v2)) prime[cnt++] = v2;
            }
        }
    }
}
int solve4(){//7 8
    for(int i = 1; i <= 9; i++){
        for(int j = 0; j <= 9; j++){
            for(int k = 0; k <= 9; k++){
                for(int l = 0; l <= 9; l++){
                    int v1 = i * 1000000  + j * 100000  + k * 10000  + l * 1000  + k * 100  + j * 10  + i;
                    int v2 = i * 10000000 + j * 1000000 + k * 100000 + l * 10000 + l * 1000 + k * 100 + j * 10 + i;
                    if(is_prime(v1)) prime[cnt++] = v1;
                    if(is_prime(v2)) prime[cnt++] = v2;
                }
            }
        }
    }
}
void init(){
    solve1();solve2();solve3();solve4();
    sort(prime,prime + cnt);
}
int main(){
    freopen("pprime.in","r",stdin);
    freopen("pprime.out","w",stdout);
    init();
    scanf("%d%d",&a,&b);
    for(int i = 0; i < cnt; i++)
        if(prime[i] >= a && prime[i] <= b)
            printf("%d\n",prime[i]);
    return 0;
}


【USACO】Prime Palindromes(暴力暴力再暴力)

标签:

原文地址:http://blog.csdn.net/u013451221/article/details/45047649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!