欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > P1217 [USACO1.5] 回文质数 Prime Palindromes

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

2024/10/24 4:34:47 来源:https://blog.csdn.net/Beilin_LeBron/article/details/141713810  浏览:    关键词:P1217 [USACO1.5] 回文质数 Prime Palindromes

题目描述

因为 151 151 151 既是一个质数又是一个回文数(从左到右和从右到左是看一样的),所以 151 151 151 是回文质数。

写一个程序来找出范围 [ a , b ] ( 5 ≤ a < b ≤ 100 , 000 , 000 ) [a,b] (5 \le a < b \le 100,000,000) [a,b](5a<b100,000,000)(一亿)间的所有回文质数。

输入格式

第一行输入两个正整数 a a a b b b

输出格式

输出一个回文质数的列表,一行一个。

样例 #1

样例输入 #1

5 500

样例输出 #1

5
7
11
101
131
151
181
191
313
353
373
383

提示

Hint 1: Generate the palindromes and see if they are prime.

提示 1: 找出所有的回文数再判断它们是不是质数(素数).

Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.

提示 2: 要产生正确的回文数,你可能需要几个像下面这样的循环。

题目翻译来自NOCOW。

USACO Training Section 1.5

产生长度为 5 5 5 的回文数:

for (d1 = 1; d1 <= 9; d1+=2) {    // 只有奇数才会是素数for (d2 = 0; d2 <= 9; d2++) {for (d3 = 0; d3 <= 9; d3++) {palindrome = 10000*d1 + 1000*d2 +100*d3 + 10*d2 + d1;//(处理回文数...)}}}

思路

参考大佬题解。

代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define endl '\n'
using namespace std;int a, b;// 判断位数
// 这里用到最重要的一个性质:
// 所有偶数位的回文数(除了11)必然不是质数。
bool check_weishu(int x) {// 如果是偶数位,必然不是质数,返回falseif ((x >= 1000 & x <= 9999) || (x >= 100000 && x <= 999999)) {return false;}return true;
}// 判断回文
bool check_huiwen(int x) {vector<int> a;while (x) {a.push_back(x % 10);x /= 10;}int len = a.size();for (int i = 0; i < len / 2; i++) {if (a[i] != a[len - i - 1]) {return false;}}return true;
}// 判断质数
bool check_zhishu(int x) {if (x < 2) {return false;}for (int i = 2; i <= x / i; i++) {if (x % i == 0) {return false;}}return true;
}int main() {ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);cin >> a >> b;// 这里是为了从奇数开始枚举,因为偶数肯定不是质数(本题范围不包括2)if (a % 2 == 0) {a++;}// 本题范围最大到10^8次方(9位),8位的回文数一定不是质数,因此最多只需要枚举到9999999(7位)b = min(b, 9999999);for (int i = a; i <= b; i += 2) {// 因为判断回文快,而回文数又少,所以先判断回文,再判断质数if (check_weishu(i) && check_huiwen(i) && check_zhishu(i)) {cout << i << endl;}}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com