【数论】(贾志鹏)线性欧拉筛模板&&CODE[VS] 1453 统计素数个数2

点击进入异世界

详情请百度“贾志鹏线性筛”

每次只用最小的素数筛去,时间复杂度为线性的O(n)比埃筛快
但空间复杂度比埃筛大些

#include 
#include 
#include 
#include 
#include 
#define maxn 13333333

using namespace std;

typedef long long LL;

LL l,r;
LL n;
LL prime[maxn];
LL used[maxn];

inline LL read()
{
    char ch;
    LL data = 0;
    LL f = 1;
    while(ch <'0'|| ch >'9')
    {
        if(ch == '-')
        {
            f = -1;
        }
        ch = getchar();
    }
    do{
        data = data*10+ch-'0';
        ch = getchar();
    }while(ch >='0'&&ch <='9');

return data * f;
}

LL cnt = 0; 

inline void isprime(LL x)
{
    memset(used,0,sizeof(used));
    for(LL i = 2;i <= x;i++)
    {
        if(used[i] == 0) prime[++cnt] = i;
        for(LL j = 1;j <= cnt && i*prime[j] <= x;j++)
        {
            used[i * prime[j]] = 1;     
            //cout<
            if(i%prime[j] == 0) break;
        }
    }
}

LL ans = 0;

int main()
{

    l = read();
    r = read();
    isprime(r);
    for(LL i = 0;i <= cnt;i++)
        if(prime[i] >= l&&prime[i] <= r) ans++;
    printf("%lld\n",ans);
return 0;
}

THE END

By Peacefuldoge

http://blog.csdn.net/loi_peacefuldog

你可能感兴趣的:(素数,线性筛,筛法,【NOIP2016】,【数论】,【模板】)