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

相关推荐
你撅嘴真丑15 小时前
第九章-数字三角形
算法
在路上看风景16 小时前
19. 成员初始化列表和初始化对象
c++
uesowys16 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
zmzb010316 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder16 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮16 小时前
AI 视觉连载1:像素
算法
念风零壹16 小时前
C++ 内存避坑指南:如何用移动语义和智能指针解决“深拷贝”与“内存泄漏”
c++
智驱力人工智能16 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥17 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风17 小时前
代码随想录第十五天
数据结构·算法·leetcode