POJ 3518 (筛素数)

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

题意:给你任意一个数,求它的下一个素数和上一个素数的差,前提是这个数不是素数。若该数本事就是素数,就输出0.
思路:本题是一个比较简单的晒素数的题,最主要的是要细心。我的想法是记录该数的前一个素数和后一个素数,如果它本身就是一个素数,那么前一个素数和后一个素数都是它自己。
这样做最大的好处在于访问的时候时间复杂度是O(1)


代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <cstring>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 const int N=1300000;
 9 
10 struct node
11 {
12     bool v;      //当前素数是不是素数
13     int left;    //前一个素数
14     int right;    //后一个素数
15     int id;
16 };
17 
18 node a[N];
19 
20 void isprime()
21 {
22     for(int i=0;i<N;i++)
23     {
24         a[i].v=true;
25         a[i].id=0;
26         a[i].left=a[i].right=i;
27     }
28     a[0].v=a[1].v=false;
29     int k=1;
30     for(int i=2;i<N;i++)
31     {
32         if(a[i].v)     //i表示当前素数
33         {
34             a[i].id=k;    //上一个素数的位置
35             for(int j=2*i;j<N;j+=i)
36             {
37                 a[j].v=false;    //标记不是素数的数
38             }
39             for(int j=k+1;j<i;j++)
40             {
41                 a[j].left=k;
42                 a[j].right=i;
43             }
44             k=i;
45         }
46     }
47 }
48 
49 int main()
50 {
51     isprime();
52     int m;
53     while(~scanf("%d",&m))
54     {
55         if(m==0) return 0;
56         if(a[m].v==true)
57         {
58             printf("0\n");
59             continue;
60         }
61         int k=a[m].right-a[m].left;
62         printf("%d\n",k);
63     }
64     return 0;
65 }

 

posted @ 2016-08-08 14:11  lianyuAngel  Views(207)  Comments(0Edit  收藏  举报