习题10-4 UVA 1644 Prime Gap(素数打表+二分查找)

很简单的一道题目, 

输入一个数n,求左右相邻素数的差,若n是素数则输出0.

思路:

素数打表,打表的同时,把是素数的装到vector里面,

最后二分查找即可!


代码如下:


#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;
const int maxn = 1500000;
int vis[maxn];
vector<int>v;
int my_find(int k){
    int l = 0,r = v.size()-1;
    while(l <= r){
        int mid = l + (r-l) / 2;
        if (v[mid] > k && v[mid-1] < k)return mid;
        else if (v[mid] < k)l = mid +1;
        else r = mid-1;
    }
}
int main()
{
    memset(vis,0,sizeof(vis));
    for (int i = 2; i < maxn; ++i)
        if (!vis[i]){
            v.push_back(i);
            for (int j = i+i; j < maxn; j+=i)vis[j]=1;
        }
    int k;
    while(scanf("%d",&k) == 1 && k){
        if (!vis[k])cout << 0 << endl;
        else{
            int key = my_find(k);
            cout << v[key]-v[key-1] << endl;
        }
    }
    return 0;
}


你可能感兴趣的:(C语言,uva)