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 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
River4162 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥5 小时前
C++ std::set
c++
Fanxt_Ja5 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下5 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶6 小时前
算法 --- 字符串
算法
博笙困了6 小时前
AcWing学习——差分
c++·算法
NAGNIP6 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP6 小时前
大模型微调框架之LLaMA Factory
算法
echoarts6 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust