Prime Gap
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 9811 Accepted: 5650
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
Japan 2007
题意:给定一个数n,求包含n的两个相邻素质的距离即差值,n为素数时距离为零。
思路:题中给定n不超过1299709,故可以用二分找到n左右的第一个素数,可以直接写一个基本的isPrime函数判断一个数是不是素数,本题中这种方法似乎更高效,这里,用打印素数表的方式把2到1299709之间的所有素数放到一个数组primeTable里,若n是素数输出0否则只要找到primeTable[i] < n 且primeTable[i+1]大于n,再用primeTable[i+1] - primeTable[i]即所求Gap.
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
#define debug(x) cout << "--------------> " << x << endl
using namespace std;
const double PI = acos(-1.0);
const double eps = 1e-10;
const long long INF = 0x7fffffff;
const long long MOD = 1000000007;
const int MAXN = 1299709 + 7;
int num[MAXN] = {0}, primeTable[MAXN]={0};
int index = 0;
void init() //打印素数表
{
int i, j;
for(i=1;i<=MAXN;i++)
num[i]=1;
for(i=2;i<=MAXN;i++)
if(num[i])
for(j=i+i;j<=MAXN;j+=i)
num[j]=0;
for(i=2;i<=MAXN;i++)
if(num[i])
primeTable[index++] = i;
}
int main()
{
init();
int n;
while(scanf("%d", &n), n)
{
if(num[n]) //n是素数
{
printf("0\n");
continue;
}
/*
for(int i = 0; i < 10; ++i)
debug(primeTable[i]);*/
int *pos = lower_bound(primeTable, primeTable+index, n);
// debug(*pos);
printf("%d\n", *pos - *(pos-1));
}
return 0;
}