集训第十二天(2017/8/11):刷题(二分法)

来源:互联网 发布:现代通信网络试题 编辑:程序博客网 时间:2024/05/21 19:28

     今天还是刷二分法的题,又做了一道莫名其妙的题,用scanf输入的话能ac,用cin输入就runtime error,我真的不知道这是什么情况??贴上这道题(通过这道题也收获了很多,比如说筛法求素数这道题,也是一道挺好的题),有没有大佬知道怎么解决?

    

Prime Gap

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 30   Accepted Submission(s) : 24
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<cstdio>
using namespace std;
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 k=2;k<=1300000;k++)
      {
          if(prime[k]) primenum[num++]=k;
      }
    return num;
}
int main()
{
    int num=isprime();
    int n;
    while(scanf("%d",&n)!=EOF && n)//while(cin>>n&&n)运行时错误?!
    {
        if(prime[n])
        {
            cout<<0<<endl;
            continue;
        }
        else
         for(int i=0;i<num;i++)
        {
            if(primenum[i]<n&&primenum[i+1]>n)
              cout<<(primenum[i+1]-primenum[i])<<endl;
        }
    }
    return 0;
}

原创粉丝点击