poj Prime Gap

Prime Gap
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 6070   Accepted: 3454

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

学习了一种叫做prime gap的东西;
View Code
 1 #include <iostream>
2 #include <cstring>
3 #include <cstdio>
4 using namespace std;
5 const int N=1299709+10;
6 int prime[100010],num;
7 bool isprime[N];
8 void find_prime()
9 {
10 memset(isprime,0,sizeof(isprime));
11 num=0;
12 for(int i=2;i<1299714;i++)
13 {
14 if(!isprime[i])
15 {
16 for(int j=2*i;j<1299714;j+=i)
17 {
18 isprime[j]=1;
19 }
20 prime[num++]=i;
21 }
22 }
23 }
24
25 int find(int key)
26 {
27 int l=0,r=num-1,ans=0;
28 while(l<=r)
29 {
30 int mid=(l+r)>>1;
31 if(prime[mid]<=key)
32 {
33 ans=mid;
34 l=mid+1;
35 }
36 else
37 r=mid-1;
38 }
39 return ans;
40 }
41 int main()
42 {
43 find_prime();
44 int n;
45 //cout<<num<<endl;
46 while(cin>>n&&n)
47 {
48 if(!isprime[n])
49 puts("0");
50 else
51 {
52 int pos=find(n);
53 printf("%d\n",prime[pos+1]-prime[pos]);
54 }
55 }
56 return 0;
57 }


posted on 2011-10-29 19:51  Goal  阅读(177)  评论(0编辑  收藏  举报

导航