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

相关推荐
香蕉卜拿拿拿1 天前
软件解耦与扩展的利器:基于C++与C#的插件式开发实践
c++
aigcapi1 天前
RAG 系统的黑盒测试:从算法对齐视角解析 GEO 优化的技术指标体系
大数据·人工智能·算法
苏宸啊1 天前
链式二叉树基操代码实现&OJ题目
数据结构
风筝在晴天搁浅1 天前
hot100 25.K个一组翻转链表
数据结构·链表
CoderCodingNo1 天前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
柯慕灵1 天前
7大推荐系统/算法框架对比
算法·推荐算法
adam-liu1 天前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
小十一再加一1 天前
【初阶数据结构】栈和队列
数据结构
栀秋6661 天前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
如果你想拥有什么先让自己配得上拥有1 天前
数学思想和数学思维分别都有什么?
线性代数·算法·机器学习