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

· · 题解

P1217 题解:

主要思路:

* 因为回文数数量少于质数,所以优先判断回文,再判断质数。 ## 代码实现: * 输入 $a,b$ 的值。 * 定义判断质数的函数 $prime$ 判断质数。 * 用字符串 $reverse$ 函数判断回文数。 * 循环判断并输出结果。 ~~判断质数和回文数的代码应该都会吧。。。~~ **[AC](https://www.luogu.com.cn/record/199631425) code:** ```cpp #include <bits/stdc++.h> using namespace std; int a,b; bool prime(int n){ for(int i=2;i<=sqrt(n);i++){ if(n%i==0){ return false; } } return true; }//质数判断 signed main(){ ios::sync_with_stdio(0); cin.tie(0);cout.tie(0); cin>>a>>b; if(a==2){ cout<<2<<endl; }//特判 if(a%2==0){ a++; }//偶数不可能为质数 b=min(9999999,b);//修改 b 的值 for(int i=a;i<=b;i+=2){ //判断回文数 string s,t; s=to_string(i); t=s; reverse(s.begin(),s.end()); if(t==s){ if(prime(i)){ cout<<i<<endl; } } } return 0; } ``````