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

相关推荐
小飞猪Jay35 分钟前
C++面试速通宝典——13
jvm·c++·面试
Kalika0-01 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
代码雕刻家1 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
sp_fyf_20241 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-02
人工智能·神经网络·算法·计算机视觉·语言模型·自然语言处理·数据挖掘
rjszcb2 小时前
一文说完c++全部基础知识,IO流(二)
c++
小字节,大梦想2 小时前
【C++】二叉搜索树
数据结构·c++
吾名招财2 小时前
yolov5-7.0模型DNN加载函数及参数详解(重要)
c++·人工智能·yolo·dnn
我是哈哈hh3 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
憧憬成为原神糕手3 小时前
c++_ 多态
开发语言·c++
郭二哈3 小时前
C++——模板进阶、继承
java·服务器·c++