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

P1217 [USACO1.5] 回文质数 Prime Palindromes - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

[USACO1.5] 回文质数 Prime Palindromes

题目描述

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

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

输入格式

第一行输入两个正整数 ab

输出格式

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

样例 #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

cpp 复制代码
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'

using namespace std;

typedef pair<int, int> PII;
typedef long long ll;

const int N = 100000010;

bool st[N];
int primes[5761460], cnt;
//vector<int>primes;

void get(int n)
{
	for(int i = 2; i <= n; i ++)
	{
		if(!st[i])primes[cnt ++] = i;
		for(int j = 0; primes[j] <= n / i; j ++)
		{
			st[primes[j] * i] = true;
			if(i % primes[j] == 0)break;
		}
	}
}

int main()
{
	IOS
	int a, b;
	cin >> a >> b;
	
	get(b);
	
	int ans = 0;
	for(int i = 0; i < cnt; i ++)
	{
		if(primes[i] >= a)
		{
			int x = primes[i], y = 0;
			while(x)
			{
				y = y * 10 + x % 10;
				x /= 10;
			}
			if(primes[i] == y)
			{
				cout << primes[i] << endl;
			}
		}
	}
	
	return 0;
}

线性筛1e8时间复杂度刚好能过,存primes时最好静态开点,直接开一个vector的话会MLE

相关推荐
nju_spy3 分钟前
力扣每日一题(四)线段树 + 树状数组 + 差分
数据结构·python·算法·leetcode·面试·线段树·笔试
xie0510_6 分钟前
排序算法
数据结构·算法·排序算法
guygg8810 分钟前
基于自适应傅里叶分解(AFD)及其改进算法的信号分解与重构实现
算法
黑岚樱梦17 分钟前
代码随想录打卡day25:56.合并区间
数据结构·算法
自由生长202423 分钟前
科普-BOM是什么?和UTF-8什么关系?
算法
白曦24 分钟前
switch语句的使用
c++
小年糕是糕手42 分钟前
【数据结构】常见的排序算法 -- 插入排序
c语言·开发语言·数据结构·学习·算法·leetcode·排序算法
墨染点香1 小时前
LeetCode 刷题【142. 环形链表 II】
算法·leetcode·链表
海琴烟Sunshine1 小时前
leetcode 263. 丑数 python
python·算法·leetcode
饕餮怪程序猿1 小时前
C++:大型语言模型与智能系统底座的隐形引擎
c++·人工智能