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

2021-01-22 12:44:56 浏览数 (1)

代码语言:javascript复制
#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 %dn",ans1, ans2);
        else
            puts("FAIL");
    }
    return 0;
}

0 人点赞