0分求助

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

hsy0824 @ 2024-08-15 22:25:55

#include <bits/stdc++.h>
using namespace std;
bool huiwen(int x){
    int t = x;
    int cnt = 0;
    while (t != 0){
        cnt++;
        t /= 10;
    }
    int c[10],tmp = 0;
    for (int i = 0; i <= cnt-1; i++){
        c[i] = x % 10;
        x /= 10;
        tmp++;
    }
    for (int i = 1; i <= ceil(tmp/2); i++){
        if (c[i] != c[tmp+1-i]){
            return false;
        }
    }
    return true;
}
bool zhishu(int y){
    for (int j = 2; j*j <= y; j++){
        if (y % j == 0){
            return false;
        }
    }
    return true;
}
int main(){
    int a,b;
    cin >> a >> b;
    for (int k = a; k <= b; k++){
        if (huiwen(k) == true && zhishu(k) == true){
            cout << k << "\n";
        }
    }
    return 0;
}

by haimingbei @ 2024-08-15 22:29:41

@hsy0824 (AC,求关)

#include<bits/stdc++.h>
using namespace std;
int a,b;
bool zs(int n){
    if(n==0||n==1)return 0;
    for(int i=2;i*i<=n;i++){
        if(n%i==0)return 0;
    }
    return 1;
}
int hws(int n){
    int a=n,s=0;
    while(a){
        s=s*10+a%10;
        a/=10;
    }
    return s;
}

int main(){
    cin>>a>>b;
    if(a%2==1){
        for(int i=a;i<=b;i+=2){
            if(i==hws(i)){
                if(zs(i)==1)cout<<i<<endl;
            }
        }
    }
    else {
        for(int i=a+1;i<=b;i+=2){
            if(i==hws(i)){
                if(zs(i)==1)cout<<i<<endl;
            }
        }
    }
    return 0;
}

by hanxiaofensheng @ 2024-08-15 22:45:49

你居然比我先发表了, 不是,你写程序那么快吗? @haimingbei

#include<bits/stdc++.h>
using namespace std;
int prime(int n){
    if(n==1)return 0;
    if(n%2==0) return 0;
    else { 
        int i;
        for(i=2; i<=sqrt(n); i++) if(n%i==0)return 0;
        return 1;
    }
}
int hw(int n) { 
    int sum=0;
    int k=n;
    while(n!=0) {
        sum=sum*10+n%10;
        n/=10;
    }
    if(sum==k)return 1;
    else return 0;
}
int main() {
    int i,n,sum=0,m;
    cin>>n>>m;   
    for(i=n; i<=m; i++) {
        if(i==9989900) break;
        if(hw(i)&&prime(i)) cout<<i<<endl; 
    }
    return 0; 
}

求求了关注我吧


|