44分,5个超时

P1217 [USACO1.5] 回文质数 Prime Palindromes

lrqSB @ 2024-08-21 09:52:13


#include<bits/stdc++.h>
using namespace std;
int main() {
    int b=0, c = 0, v = 0, f,m;
    int a[10];
    int min, max, h=0;
    cin >> min >> max;
    for (int i = min; i <= max; i++) {
        for (int j = 1; j <= sqrt(i); j++) {
            if (i % j == 0) {
                h++;
            }
        }
        if (i <= 9) {
            f = 1;
        }
        if (i > 9 && i <= 99) {
            f = 2;
        }
        if (i > 99 && i <= 999) {
            f = 3;
        }
        if (i > 999 && i <= 9999) {
            f = 4;
        }
        if (i > 9999 && i <= 99999) {
            f = 5;
        }
        if (i > 99999 && i <= 999999) {
            f = 6;
        }
        if (i > 999999 && i <= 9999999) {
            f = 7;
        }
        if (i > 9999999 && i <= 99999999) {
            f = 8;
        }
        if (i > 99999999 && i <= 999999999) {
            f = 9;
        }
        for(int u=0;u<f;u++){
                    m=(pow(10,u));
                    a[u]=(i/m) %(10);
                }
        for (int k = 1; k <= f; k++) {
            if (a[k - 1] == a[f - k]) {
                b++;
            }
        }

        if (h == 1 && b == f ) {
            cout << i << endl;
        }
        h=0;
        b=0;
    }
}

by lrqSB @ 2024-08-21 09:55:09

很赖的写法,不是吗,先判断位数,再判断素数和回文数。


by Perry6632 @ 2024-08-21 10:07:30

用筛


by Emil_ @ 2024-08-21 10:08:58

@lion0617

#include<bits/stdc++.h>
using namespace std;
bool huiwen(int n){
    bool r=true;
    int w[15]={};
    int k=1;
    while(n>0){
        w[k]=n%10;
        k++;
        n/=10;
    }
    for(int i=1;i<=k;i++){
        if(w[i]!=w[k-i]){
            r=false;
        }
    }
    return r;
}
int main(){
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0); 
    int a,b;
    cin>>a>>b;
    for(int i=a;i<=b;i++){
        if(i%2==0){
            i++;
        }
        if(huiwen(i)==true){
            bool f=true;
            for(int j=2;j<=sqrt(i);j++){
                if(i%j==0)
                    f=false;
            }
            if(f)
                cout<<i<<endl;
        }
    }
    return 0;
}

by lrqSB @ 2024-08-21 10:12:39

@Emil_ 懂了


by Emil_ @ 2024-08-21 10:13:51

@lion0617

qiuguan


by lrqSB @ 2024-08-21 10:14:09

@Emil_,std::ios::sync_with_stdio(0);但这句不懂


by hhztl @ 2024-08-21 10:14:48

@lion0617 快读


by lrqSB @ 2024-08-21 10:15:12

cin.tie(0); cout.tie(0); 包括这句


by hhztl @ 2024-08-21 10:15:41

@lion0617 这两句都是快读


by lrqSB @ 2024-08-21 11:03:35

@Emil_ qiuguan,什是么意思


| 下一页