Prime number density (find the number of prime numbers in the interval)

Title Portal

Topic:
Give you an interval, find the number of prime numbers in this interval.
Data range
(L≤R≤2147483647, RL≤1000000)

The
interval is in the range of int, so the maximum prime factor of a number will not exceed 5e4. But pay attention to the length of the interval, if we traverse the interval, and then judge one by one, please mention TLE. However, the general sieve method can not handle this data range, so we will find another way.
As mentioned earlier, the largest prime factor of any number in the interval does not exceed 50000, then we can first use the sieve method to find the prime numbers within 50000, and then use these prime numbers to screen the numbers in the interval, so that there is no need to deal with irrelevant data. .

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
const int inf=0x7fffffff;
const int mod=1e9+7;
const int eps=1e-6;
typedef long long ll;
typedef unsigned long long ull;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl '\n'
bool ok[N];
int p[N];
int cnt=0;
bool isp[N];
void f()
{
    for(int i=2;i<=50000;i++)
    {
        if(!ok[i])
        {
            p[++cnt]=i;
            for(int j=i*i;j<=50000;j+=i)
            {
                ok[j]=1;
            }
        }
    }
}
signed main()
{
    IOS;
    int l,r;
    cin>>l>>r;
    f();
    for(int i=1;i<=cnt&&p[i]<=r;i++)
    {
        for(int j=l/p[i]*p[i];j<=r;j+=p[i])
        {
            if(j==p[i]||j<l)
            {
                continue;
            }
            isp[j-l]=1;
        }
    }
    int crt=0;
    for(int i=l;i<=r;i++)
    {
        if(isp[i-l]==0)
        {
            crt++;
        }
    }
    cout<<crt<<endl;
}

Published 93 original articles · won praise 9 · views 4203

Guess you like

Origin blog.csdn.net/Joker_He/article/details/104884002