0
点赞
收藏
分享

微信扫一扫

hdu6 1001 Yes, Prime Minister

全栈学习笔记 2022-03-12 阅读 26
c++算法

思路:素数筛+二分

Accode:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <map>
using namespace std;
typedef long long ll;
const int maxn = 1e8 + 10;
bool vis[maxn];
int primes[maxn];
int cnt;

void get_primes(int n)
{
    vis[0] = vis[1] = 1;
    for (int i = 2; i <= n; i ++ )
    {
        if (!vis[i]) primes[cnt ++ ] = i;
        for (int j = 0; primes[j] <= n / i; j ++ )
        {
            vis[primes[j] * i] = 1;
            if (i % primes[j] == 0) break;
        }
    }
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    get_primes(maxn);
    int T;
    cin >> T;
    while (T -- )
    {
        int x;
        cin >> x;
        if (x > 0 && !vis[x])
        {
            cout << 1 << endl;
            continue;
        }
        if (x > 0 && (!vis[x + x + 1] || !vis[x + x - 1]))
        {
            cout << 2 << endl;
            continue;
        }
        if (x < 0) x = -x;
        for (int i = x + 1; ; i ++ )
        {
            if (!vis[i])
            {
                cout << 2 * (i - 1) + 2 << endl;
                break;
            }
            if (!vis[i + i + 1])
            {
                cout << 2 * (i - 1) + 3 << endl;
                break;
            }
        }
    }

    return 0;
}
举报

相关推荐

0 条评论