1. 程式人生 > >POJ 3518 Prime Gap(素數)

POJ 3518 Prime Gap(素數)

for org 篩選法求素數 lan article sizeof tar eof rim

POJ 3518 Prime Gap(素數)

http://poj.org/problem?

id=3518

題意:

給你一個數。假設該數是素數就輸出0. 否則輸出比這個數大的素數與比這個數小的素數的差值。

分析:

明顯本題先要用篩選法求出130W(嚴格的話應該是求第100001個素數)以內的全部素數。

然後推斷給的數是否是素數就可以。

假設不是素數。那麽就找出它在素數素組內的上界和下界,輸出兩個素數的差值就可以。

篩選法求素數可見:

http://blog.csdn.net/u013480600/article/details/41120083

AC代碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1300000;

int prime[maxn+5];
int get_prime()
{
    memset(prime,0,sizeof(prime));
    for(int i=2;i<=maxn;i++)
    {
        if(!prime[i]) prime[++prime[0]]=i;
        for(int j=1;j<=prime[0]&&prime[j]<=maxn/i;j++)
        {
            prime[prime[j]*i]=1;
            if(i%prime[j]==0)break;
        }
    }
    return prime[0];
}

int main()
{
    //生成maxn內的全部素數
    get_prime();

    int x;
    while(scanf("%d",&x)==1 && x)
    {
        int bound=lower_bound(prime+1,prime+prime[0]+1,x)-prime;
        if(prime[bound]==x) printf("0\n");
        else printf("%d\n",prime[bound]-prime[bound-1]);
    }
    return 0;
}

POJ 3518 Prime Gap(素數)