POJ3518_Prime Gap【素数】【水题】

Prime Gap
Time Limit: 5000MSMemory Limit: 65536K
Total Submissions: 8499Accepted: 4983
Description


The sequence of n − 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n. For example, ‹24, 25, 26, 27, 28› between 23 and 29 is a prime gap of length 6.


Your mission is to write a program to calculate, for a given positive integer k, the length of the prime gap that contains k. For convenience, the length is considered 0 in case no prime gap contains k.


Input


The input is a sequence of lines each of which contains a single positive integer. Each positive integer is greater than 1 and less than or equal to the 100000th prime number, which is 1299709. The end of the input is indicated by a line containing a single zero.


Output


The output should be composed of lines each of which contains a single non-negative integer. It is the length of the prime gap that contains the corresponding positive integer in the input if it is a composite number, or 0 otherwise. No other characters should occur in the output.


Sample Input


10
11
27
2
492170
0
Sample Output


4
0
6
0

114

题目大意:两个连续素数a和b之间的区间称为非素数区间(包括后边的素数b)。

给你一个数N,求N所在非素数区间的长度。

如素数 23~29  之间的非素数区间为24 25 26 27 28 +素数29。非素数区间长度为6(5+1)

给你一个数25 则25所在的非素数区间长度就为6

思路:

用筛法求素数打表,用PrimeNum存放所有素数。

若N为素数,则输出长度为0

若N为合数,则找出相邻的两个素数,输出长度为两素数的差

#include<stdio.h>

int Prime[1300000],PrimeNum[100010];

int IsPrime()
{
    for(int i = 2; i <= 1300000; i++)
        Prime[i] = 1;
    for(int i = 2; i <= 1300000; i++)
    {
        for(int j = i+i; j <= 1300000; j+=i)
            Prime[j] = 0;
    }
    int num = 0;
    for(int i = 2; i <= 1300000; i++)
    {
        if(Prime[i])
            PrimeNum[num++] = i;
    }
    return num;
}


int main()
{
    int n;
    int num = IsPrime();
    while(~scanf("%d",&n) && n)
    {
        if(Prime[n])
        {
            printf("0\n");
            continue;
        }
        else
        {
            for(int i = 0; i < num; i++)
            {
                if(PrimeNum[i] < n && PrimeNum[i+1] > n)
                    printf("%d\n",PrimeNum[i+1]-PrimeNum[i]);
            }
        }
    }

    return 0;
}



你可能感兴趣的:(POJ3518_Prime Gap【素数】【水题】)