Interval prime number

Travel 2 days, came back to this question the way the AC.

P1865 A % B Problem

The title tells a range: the range extremes are -1e9 and 1e9 (this is the test data teasing you, there can be no actual topic negative), both ends of the range from a maximum of 1e6.

L or said title r∉ [1, m] output Crossing the line, then converted to the title number of the prime requirements between l ~ r, l is the minimum 1, r max 1e6.

It can be considered an array of open 1e6 able to save all of the primes between 0 ~ 1e6, sieved with a sieve of formula Angstroms, sum accumulated click. sum [r] -sum [l] is the answer.

An important note - note the opening and closing intervals: an interval such as [2,9], the simple sum [r] -sum [l] get three, in fact, the answer to 2 is also a prime number, but was subtracted, it is necessary special sentenced to the left end zone is prime, then the answer is +1. Without it only take 36 minutes.

#include<bits/stdc++.h>
using namespace std;
int n,m,l,r,sum[1000005],t;
bool a[1000005]= {1,1};
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=2; i<=m; i++)
        for(int j=i; j<=m; j=j+i)
            if(i%j!=0)a[j]=1;
    for(int i=1; i<=m; i++)
        if(!a[i])sum[i]++;
    for(int i=1; i<=m; i++)
        sum[i]+=sum[i-1];
    for(int i=1; i<=n; i++)
    {
        scanf("%d%d",&l,&r);
        if(l>m||l<1||r>m||r<1)
        {
            cout<<"Crossing the line"<<endl;
            continue;
        }
        if(r==1)
        {
            cout<<0<<endl;
            continue;
        }
        t=sum[r]-sum[l];
        if(!a[l])t++;
        printf("%d\n",t);
    }
    return 0;
}
AC

 

Guess you like

Origin www.cnblogs.com/yige2019/p/11291485.html