Prime Gap--(二分)

来源:互联网 发布:python2.6抓取网页数据 编辑:程序博客网 时间:2024/05/22 15:30

Prime Gap

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 11   Accepted Submission(s) : 9
Problem 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 + nis 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
<p>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.</p>
 

Output
<p>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.</p>
 

Sample Input
10112724921700
 

Sample Output
4060114

筛素数经行预处理,对下标二分

代码:

#include<iostream>#include<string>#include<cstdio>#include<algorithm>#include<cmath>#include<iomanip>#include<queue>#include<cstring>#include<map>using namespace std;#define inf 1000000int n,a[100005];bool ok[1299730];int main(){    int i,j,num=0;    memset(ok,true,sizeof(ok));    ok[0]=ok[1]=false;    for(i=2;i<1299730;i++)    {        if(ok[i])        {            for(j=2*i;j<1299730;j+=i)                ok[j]=false;            a[++num]=i;        }    }    while(scanf("%d",&n)&&n)    {        int left=1,right=num,mid;        while(left<num)        {            mid=(left+right)/2;            if(a[mid]==n) {printf("0\n"); break;}            if(a[mid]<n&&a[mid+1]>n) {printf("%d\n",a[mid+1]-a[mid]); break;}            if(a[mid]>n) right=mid-1;            else left=mid+1;        }    }    return 0;}


原创粉丝点击