[大区间素数] lightoj 1197

题意

求a – b之间的素数个数

思路

先分别做好[2,sqrt(b))的表和[a,b)的表,然后从[2,sqrt(b))的表中筛得素数的同时,也将其倍数从[a,b)的表中划去

代码

// https://blog.csdn.net/qq_32866009/article/details/76945320

#include 
#include 
#include 
#include 

typedef long long LL;

using namespace std;

const int N = 1000007;

bool small_prime[ N ];
bool intervel_prime[ N ];

void init () {
    memset ( small_prime, true, sizeof ( small_prime ) );
    small_prime[ 0 ] = small_prime[ 1 ] = false;

    for ( int i = 2; i < (int)sqrt ( N ); ++i ) {
        if ( small_prime[ i ] )
            for ( int j = i + i; j * j < N; j += i )
                small_prime[ j ] = false;
    }
}

void segment_sieve ( LL a, LL b ) {
    memset ( intervel_prime, true, sizeof ( intervel_prime ) );

    if ( a == (LL)1 )
        intervel_prime[ 0 ] = false;

    for ( int i = 2; i <= (int)sqrt ( b ); ++i ) {
        if ( small_prime[ i ] ) {
            for ( LL j = max ( (LL)2, ( a + i - 1 ) / i ) * i; j <= b; j += i )
                intervel_prime[ j - a ] = false;
        }
    }
}

int main () {
    int T;
    scanf ( "%d", &T );
    init ();
    for ( int ks = 1; ks <= T; ++ks ) {
        LL a, b;
        scanf ( "%lld%lld", &a, &b );
        segment_sieve ( a, b );

        int cnt = 0;
        for ( int i = 0; i <= b - a; ++i ) {
            if ( intervel_prime[ i ] )
                ++cnt;
        }

        printf ( "Case %d: %d\n", ks, cnt );
    }
    return 0;
}

你可能感兴趣的:(ACM,14-数论基础)