Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 10713 | Accepted: 6165 |
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
Regionals 2007 >> Asia - Tokyo
问题链接:POJ3518 UVA1644 UVALive3883 Prime Gap
问题简述:
两个连续素数a和b之间的区间称为非素数区间(包括后边的素数b)。输入n,计算n所在非素数区间的长度。
例如,素数 23~29 之间的非素数区间为24 25 26 27 28 和素数29。非素数区间长度为6(5+1)。输入给整数25,则25所在的非素数区间长度就为6。
问题分析:
筛选法是必要的,先找出素数。
打表是套路,也是必须的。
程序说明:(略)
题记:(略)
参考链接:(略)
AC的C++语言程序如下:
/* POJ3518 UVA1644 UVALive3883 Prime Gap */
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
const int N = 1299709 + 1;
const int SQRTN = ceil(sqrt((double) N));
bool prime[N + 1];
int ans[N];
// Eratosthenes筛选法
void esieve(void)
{
memset(prime, true, sizeof(prime));
prime[0] = prime[1] = false;
for(int i = 2; i <= SQRTN; i++) {
if(prime[i]) {
for(int j = i * i; j <= N; j += i) //筛选
prime[j] = false;
}
}
}
void maketable()
{
for(int i = 2; i < N; i++) {
if(!prime[i]) {
int j = i;
while(j < N && !prime[j])
j++;
j--;
for(int k = i; k <= j; k++)
ans[k] = j - i + 2;
i = j;
} else
ans[i] = 0;
}
}
int main()
{
ios::sync_with_stdio(false);
esieve();
maketable();
int n;
while(cin >> n && n)
cout << ans[n] << endl;
return 0;
}