ACM:L: 素数槽

来源:互联网 发布:淘宝网服务中心 编辑:程序博客网 时间:2024/06/05 14:24

ACM:L: 素数槽

Description

       处于相邻的两个素数pp + n之间的n - 1个连续的合数所组成的序列我们将其称为长度为n的素数槽。例如,‹24, 25, 26, 27, 28›是处于素数23和素数29之间的一个长度为6的素数槽。

       你的任务就是写一个程序来计算包含整数k的素数槽的长度。如果k本身就是素数,那么认为包含k的素数槽的长度为0。

Input

第一行是一个数字n,表示需要测试的数据的个数。后面有n行,每行是一个正整数k, k大于1并且小于或等于的第十万个素数(也就是1299709)。

Output

对于输入部分输入的每一个k,都对应输出一个非负整数,表示包含k的素数槽的长度,每个非负整数占一行。

Sample Input

5
10
11
27
24
92170

Sample Output

4
0
6
0
114
注:直接暴力求解,明显超时,用素数打表法,效率超快
素数打表法: 如2是素数,则2+2,2+2+2,...都不是素数
               3是素数,则3+3,3+3+3,...都不是素数
       5是素数,则5+5,5+5+5,...都不是素数

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <ctime>
#define LL long long
#define MAX(a,b)((a)>(b)?a:b)
#define MIN(a,b)((a)<(b)?a:b)
#define INF 0x7ffffff
#define N 1300005
#define M 15
using namespace std;
int pri[N];
//素数打表法
void priTable()
{
    memset(pri,1,sizeof(pri));
    int n=(int)(sqrt(N+0.5));
    for(int i=2;i<=n;i++)
        for(int j=i*2;j<=N;j=i+j)
            pri[j]=0;
}
int main()
{
    int T;
    int k;
    cin>>T;
    priTable();
    while(T--)
    {
        cin>>k;
        int top=k,floor=k;
        while (!pri[top]) {
            top++;
        }
        while(!pri[floor]){
            floor--;
        }
        cout<<top-floor<<endl;
    }
    return 0;
}