P1217 [USACO1.5] 回文質數 Prime Palindromes - 洛谷 | 計算機科學教育新生態 (luogu.com.cn)
# [USACO1.5] 回文質數 Prime Palindromes
## 題目描述
因為 $151$ 既是一個質數又是一個回文數(從左到右和從右到左是看一樣的),所以 $151$ 是回文質數。
寫一個程序來找出范圍 $[a,b] (5 \le a < b \le 100,000,000)$(一億)間的所有回文質數。
## 輸入格式
第一行輸入兩個正整數 $a$ 和 $b$。
## 輸出格式
輸出一個回文質數的列表,一行一個。
## 樣例 #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
#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()
{IOSint 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