Problems with a large bool array in C #

I decided to write a prime generator as a lightweight executive. 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 fine with input of type 1..10000. However, at about max = 1,000,000,000, it begins to work EXTREMELY slowly; In addition, mono takes up about 1 GB of memory. This seems strange to me: shouldn't bool [1,000,000,000] accept 1,000,000,000 bits, not bytes? Maybe I'm making some kind of stupid mistake that I don’t see that makes it so ineffective?

+4
source share
2 answers

Nope. Unlike C ++ vector<bool> , in C # the bool array is, well, the bools array.

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

+4
source

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

+8
source

Source: https://habr.com/ru/post/1414936/


All Articles