10

hdoj 4715 Difference Between Primes 素数筛选+二分查找

 2 years ago
source link: https://zxs.io/article/177
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
hdoj 4715 Difference Between Primes 素数筛选+二分查找
#include <string.h>
#include <stdio.h>
const int maxn = 1000006;
bool vis[1000006];
int pr[1000005];
int cnt = 1;

int bs(int l, int r, int v)
{
    int mid=(l+r)>>1;
    while(l < r)
    {
        if(pr[mid] < v)
            l = mid+1;
        else
            r = mid;
        mid= (l+r) >> 1;
    }
    return l;
}

void getpr()
{
    int i,j;
    for(i=2;i*i<maxn;i++) if(!vis[i])
    {
        pr[cnt++]=i;
        for(j=i*i;j<maxn;j+=i) vis[j]=1;
    }
    for(;i<maxn;i++)if(!vis[i])
    {
        pr[cnt++]=i;
    }
}

int main()
{
    memset(vis, 0, sizeof(vis));
    getpr();
    int n, t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        int ans1 = 0;
        int ans2 = 0;
        for (int i = 1; i <= cnt; i++)
        {
            if (pr[i] <= n)
                continue;
            int x = bs(1, cnt-1, pr[i]-n);
            if (pr[i] - n == pr[x])
            {
                ans1 = pr[i];
                ans2 = pr[x];
                break;
            }
        }
        if (ans1)
            printf("%d %d\n",ans1, ans2);
        else
            puts("FAIL");
    }
    return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK