51nod--1181 质数中的质数(质数筛法)

题目

1181 质数中的质数(质数筛法)
题目来源: Sgu
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
如果一个质数,在质数列表中的编号也是质数,那么就称之为质数中的质数。例如:3 5分别是排第2和第3的质数,所以他们是质数中的质数。现在给出一个数N,求>=N的最小的质数中的质数是多少(可以考虑用质数筛法来做)。
Input
输入一个数N(N <= 10^6)
Output
输出>=N的最小的质数中的质数。
Input示例
20
Output示例
31

分析:

直接筛选质数, 然后判断是否为质数中的质数, 加入数组。 查找用二分查找即可。

实现:

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const LL maxn = 2000000 + 131;

bool Jug[maxn];
vector<LL> Prime;
vector<LL> PrimeInPrime;
vector<LL>::iterator tmp;

void Make() {
    int cnt = 0;
    memset(Jug, false, sizeof(Jug));
    Jug[0] = Jug[1] = true;
    Prime.clear();
    PrimeInPrime.clear();
    for(LL i = 2; i < maxn; ++i)
    {
        if(Jug[i] == false) {
            Prime.push_back(i);
            cnt ++;
            if(Jug[cnt] == false) PrimeInPrime.push_back(i);
            for(LL j = i + i; j < maxn; j += i) Jug[j] = true;
        }
    }
}

int main() {
    LL N;
    Make();
    while(cin >> N) {
        tmp = lower_bound(PrimeInPrime.begin(), PrimeInPrime.end(), N);
        cout << *tmp << endl;
    }
}
原文地址:https://www.cnblogs.com/aoxuets/p/5506838.html