今天还是刷二分法的题,又做了一道莫名其妙的题,用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
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.
10 11 27 2 492170 0
4 0 6 0 114
#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;
}