# 8.5 第六场 Yes, Prime Minister
8.5 第六场 Yes, Prime Minister
Time Limit: 10000/10000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 926 Accepted Submission(s): 335
Problem Description
Mr. Hacker’s Department of Administrative Affairs (DAA) has infinite civil servants. Every integer is used as an id number by exactly one civil servant. Mr. Hacker is keen on reducing overmanning in civil service, so he will only keep people with consecutive id numbers in [l,r] and dismiss others.
However, permanent secretary Sir Humphrey’s id number is x and he cannot be kicked out so there must be l≤x≤r. Mr. Hacker wants to be Prime Minister so he demands that the sum of people’s id number ∑ri=li must be a prime number.
You, Bernard, need to make the reduction plan which meets the demands of both bosses. Otherwise, Mr. Hacker or Sir Humphrey will fire you.
Mr. Hacker would be happy to keep as few people as possible. Please calculate the minimum number of people left to meet their requirements.
A prime number p is an integer greater than 1 that has no positive integer divisors other than 1 and p.
Input
The first line contains an integer T(1≤T≤106) - the number of test cases. Then T test cases follow.
The first and only line of each test case contains one integer xi(−107≤xi≤107) - Sir Humphrey’s id number.
Output
For each test case, you need to output the minimal number of people kept if such a plan exists, output −1 otherwise.
Sample Input
10
-2
-1
0
1
2
3
4
5
6
7
Sample Output
6
4
3
2
1
1
2
1
2
1
大概题意:
给出x
,求附近最小和为质数的个数。
思路:
坑较多。。。需要多情况考虑,注意负数对应答案,不会有输出-1
的情况
代码:
#include<iostream>
using namespace std;
const int N = 21000010;
int primes[N], cnt; // primes[]存储所有素数
bool st[N]; // st[x]存储x是否被筛掉
void get_primes(int n) {
st[1] = true;
st[0] = true;
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() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
get_primes(21000000);
int t, n, k = 0;
cin >> t;
while (t--) {
cin >> n;
int res = 1;
if (n < 0) {
res += 2 * (0 - n) + 1;
n = 1 - n;
if (!st[n])
cout << res << endl;
else {
while (st[n] && st[n * 2 + 1]) {
n++;
res += 2;
}
if (!st[n])
cout << res << endl;
else
cout << 1 + res << endl;
}
} else if (n == 0) {
cout << 3 << endl;
continue;
}
else if (n == 1) {
cout << 2 << endl;
continue;
}
else {
if (!st[n])
cout << 1 << endl;
else if ((!st[n * 2 + 1]) || (!st[n * 2 - 1]))
cout << 2 << endl;
else {
res = n * 2 + 1;
n++;
res++;
while (st[n] && st[n * 2 + 1]) {
n++;
res += 2;
}
if (!st[n])
cout << res << endl;
else
cout << 1 + res << endl;
}
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效