Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with large bool array in C#

I decided to write a prime number generator as an easy excerise. The code is pretty simple:

static void generatePrimes (long min, long max)
    {

        bool[] prime = new bool[max + 1];

        for (long i=2; i<max+1; i++)
            prime [i] = true;

        for (long i=2; i<max+1; i++) {
            if (prime [i]) {
                if (i>=min)
                    Console.WriteLine (i);
                for (long j=i*2; j<max+1; j+=i)
                    prime [j] = false;
            }
        }

        Console.WriteLine ();

    }

It works just fine with input like 1..10000. However, around max=1000000000 it starts to work EXTREMELY slow; also, mono takes about 1Gb of memory. To me, it seems kinda strange: shouldn't the bool[1000000000] take 1000000000 bits, not bytes? Maybe I'm making some stupid mistake that I don't see that makes it so uneffective?

like image 277
Max Yankov Avatar asked Dec 16 '22 23:12

Max Yankov


2 Answers

The smallest unit of information a computer can address is a byte. Thus a bool is stored as a byte. You will need special code to put 8 bools in one byte. The BitArray class does this for you.

like image 65
Kendall Frey Avatar answered Dec 18 '22 12:12

Kendall Frey


Nope. Contrarily to C++'s vector<bool>, in C# an array of bool is, well, an array of bools.

If you want your values to be packed (8 bits per bool), use a BitArray instead.

like image 45
user703016 Avatar answered Dec 18 '22 12:12

user703016