码迷,mamicode.com
首页 > 其他好文 > 详细

poj 3518 Prime Gap

时间:2015-02-22 23:01:37      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

Prime Gap
 1 #include<cmath>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<string>
 6 #include<cstring>
 7 #include<vector>
 8 using namespace std;
 9 #define max 100000
10 int prime[max+5];
11 //bool vis[max+5];
12 void get_prime(int n){
13     //memset(vis,false,sizeof(vis));
14     prime[0]=2;
15     prime[1]=2;
16     int i=3,index=2;
17     for(;index<=n;i+=2){
18         //cout<<i<<endl;
19         //cout<<prime[index-1]<<endl;
20         int half=sqrt(i*1.0)+1;
21         int j=1;
22         while(j<index&&half>prime[j]){//不知道为什么j<index可以去掉。去掉也是对的。
23             //cout<<i<<" "<<j<<" "<<prime[j]<<endl;
24             if(i%prime[j]==0){
25                 break;
26             }
27             j++;
28         }
29         if(half<=prime[j]){
30             prime[index++]=i;
31         }
32     }
33     //cout<<prime[index-1]<<endl;
34 }
35 int main(){
36     int n;
37     get_prime(max);
38     while(cin>>n&&n){
39         int i=1;
40         while(prime[i]<n){
41             i++;
42         }
43         if(prime[i]==n){
44             cout<<0<<endl;
45         }
46         else{
47             cout<<prime[i]-prime[i-1]<<endl;
48         }
49     }
50     return 0;
51 }

 

Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 8766   Accepted: 5148

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

Source

 
分析:
 

poj 3518 Prime Gap

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/4297778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!