求区间 [L,R] 中素数的个数
https://atcoder.jp/contests/abc412/tasks/abc412_e
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N =1e6 + 10;
const int mod = 998244353;
int prime[N],c[N],d[N];
bool st[N];
int cnt;
signed main() 
{
    ios::sync_with_stdio(0),cin.tie(0);
    for(int i=2;i<=N;i++)    
    {
        if(!st[i]) prime[cnt++]=i;
        for(int j=0;j<cnt && prime[j]<=N/i;j++)
        {
            st[prime[j]*i]=1;
            if((i%prime[j]==0) )break;
        }
    }
    int L,R;
    cin>>L>>R;
    int ans=0;
    if(L==1)
        c[1] = 1;
    for(int i=0;i<cnt;i++)
    {
        int x=prime[i];
        int l = (L + x - 1) / x * x,r=R/x*x;
        if(l==x) l+=x;
        if(r==x)    r -= x;
        for(int j = l;j <= r;j+=x)//把【L,R】中的合数标记
        {
            c[j - L] = 1;
        }
        
    }
    
    for(int i=0;i<=R-L;i++)
    {
        if(!c[i] )
        {
            ans++;
        }
    }
    cout << ans << endl;
    return 0;
}
                    
                
                
            
        
浙公网安备 33010602011771号