区间质数

【题目描述】

区间质数个数。

【输入描述】

一行两个整数:询问次数n,范围m。

接下来n行,每行两个整数:[l,r]表示区间。

【输出描述】

对于每次询问输出个数t,如l或r∉[1,m]输出:Crossing the line。

【输入样例】

2 5

1 3

2 6

【输出样例】

2

Crossing the line

【数据范围及提示】

对于20%的数据:1<=n<=10,1<=m<=10。

对于100%的数据:1<=n<=1000,1<=m<=1000000,-10^9<=l<=r<=10^9,1<=t<=1000000。

源代码:

#include<cstdio>
int m,n,num(0);
int i[1000001];
bool f[1000001]={0};
int main() //恶心的二分查询细节。
{
    scanf("%d%d",&m,&n);
    for (int a=2;a<=n;a++) //筛法。
      if (!f[a])
      {
          i[++num]=a;
          int t=2;
          while (t*a<=n)
          {
              f[t*a]=true;
              t++;
          }
      }
    for (int a=1;a<=m;a++)
    {
        int t1,t2;
        scanf("%d%d",&t1,&t2);
        if (t1<1||t2>n)
          printf("Crossing the line
");
        else
        {
            int l(0),r(0),left=1,right=num;
            while (left<=right) //二分查询区间左位置。
            {
                int t=(left+right)>>1;
                if (i[t]>=t1)
                {
                    l=t;
                    right=t-1;
                }
                else
                  left=t+1;
            }
            left=1;
            right=num;
            while (left<=right) //二分查询区间右位置。
            {
                int t=(left+right)>>1;
                if (i[t]<=t2)
                {
                    r=t;
                      left=t+1;
                }
                else
                  right=t-1;
            }
            printf("%d
",r-l+1);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Ackermann/p/5566827.html