求助大佬

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

LMR_Minecraft @ 2024-10-05 12:12:58

头炸了,求大佬帮改

#include<iostream>
#include<string>
using namespace std;
int main() {
    string a;
    int x;
    int b[10], l, r;//l左,r右
    cin >> l >> r;
    for (int i = l; i <= r; i++) {
        x = i;
        a = to_string(i);
        reverse(a.begin(), a.end());
        i = stoi(a);
        if (i == x) {
            int num;
            for (int j = 2; j < i; j++) {
                if (i % j == 0)num++;
            }
            if (num == 0)cout << i << endl;
        }
    }
}

回复必关


by MC_dream_tsr @ 2024-10-05 14:12:55

@LMR_ 给你个思路,用int,从l到r枚举,在将,每一个数翻转过来,判断与原数相等且是否为质数


by laotingrui @ 2024-10-07 09:54:26

看看我的\ 求关~~

#include<iostream>
using namespace std;
bool tj1(int x){
    return !((x>=1000&&x<=9999)||(x>=100000&&x<=999999));//有偶数个位数的数都是11的倍数
}
//判断回文数
bool tj2(int x){
    int sum=0,p=x;
    while(x){
        sum=sum*10+x%10;
        x/=10;
    }
    return sum==p;
}
//判断质数
bool tj3(int x){
    if(x<2) return 0;
    for(int i=2;i*i<=x;i++)
        if(x%i==0) return 0;
    return 1;
}
int main(){
    int l,r;
    scanf("%d%d",&l,&r);
    if(l%2==0) l++;//从奇数开始枚举
    r=min(r,9999999);//八位数都不是质数
    for(int i=l;i<=r;i+=2)
        if(tj1(i)&&tj2(i)&&tj3(i)) printf("%d\n",i);//三个条件都满足就是回文质数
    return 0;
}

by laotingrui @ 2024-10-07 09:54:50

@LMR_


by LMR_Minecraft @ 2024-10-07 11:31:28

@laotingrui 感谢,已关


|