// This file is part of the FXT library.
// Copyright (C) 2010 Joerg Arndt
// License: GNU General Public License version 3 or later,
// see the file COPYING.txt in the main directory.

#include "ds/bitarray.h"
#include "mod/isqrt.h"

#include "fxttypes.h"

//#include "jjassert.h"


bitarray *
make_prime_bitarray(ulong n, bitarray *ba/*=0*/)
{
    if ( ba && (n!=ba->n_) )
    {
        delete ba;
        ba = 0;
    }

    if ( 0==ba )  ba = new bitarray( n );

    ba->set_all();
    ba->clear(0);
    ba->clear(1);
    // ulong n = ba->n_;
    ulong r = isqrt(n);
    ulong k = 0;
    while ( (k=ba->next_set(k+1)) < n )
    {
        if ( k > r )  break;
        for (ulong j=k*k; j<n; j+=k )  ba->clear(j);
    }

    return ba;
}
// -------------------------

bitarray *
make_oddprime_bitarray(ulong n, bitarray *ba/*=0*/)
// Sieve of Eratosthenes.
{
    if ( 0!=ba )  delete ba;
    ba = new bitarray( n/2 );

    ba->set_all();
    const ulong m = ba->n_;

    ba->clear(0);
    ulong r = isqrt(n);
    ulong i = 3;
    ulong ih = i/2;
    while ( i <= r )
    {
        if ( ba->test( ih ) )
        {
            for (ulong kh=(i*i)/2;  kh<m;  kh+=i)  ba->clear( kh );
        }
        ih = ba->next_set( ih+1 );
        i = 2*ih + 1;
    }

    return ba;
}
// -------------------------

