POJ-Prime Gap 素数筛选+二分查找

问你一个数在一个连续区间,这个区间全为和数的长度。

代码如下:

#include <cstring>

#include <cstdio>

#include <cstdlib>

#include <algorithm>

#define MAXN 1300000

using namespace std;



int p[MAXN+5], rec[100005], N;



void pre()

{

    int k;

    for (int i = 4; i <= MAXN; i += 2) {

        p[i] = 1;

    }    

    for (int i = 3; i <= 1141; i += 2) {

        if (!p[i]) {

            k = 2 * i;

            for (int j = i * i; j <= MAXN; j += k) {

                p[j] = 1;    

            }    

        }

    }

    for (int i = 2, j = 0; j <= 100000; ++i) {

        if (!p[i]) {

            rec[++j] = i;

        }

    }

}



int bsearch(int l, int r, int x, int f)

{

    int mid;

    while (l <= r) {

        mid = (l + r) >> 1;

        if (x < rec[mid]) {

            r = mid - 1;

        }

        else {

            l = mid + 1;

        }

    }    

    if (f == 1) {

        return rec[r];

    }

    else {

        return rec[l];

    }

}



int main()

{

    pre();

    int l, r;

    while (scanf("%d", &N), N) {

        if (!p[N]) {

            puts("0");

            continue;

        }

        l = bsearch(1, 100000, N, 1);

        r = bsearch(1, 100000, N, 2);

        printf("%d\n", r - l);

    }

    return 0;    

}

你可能感兴趣的:(二分查找)