Question about mpz_set_str

delta trinity deltatrinity@hotmail.com
Fri, 03 Jan 2003 18:07:48 -0500


>Hi, I want to build a GMP integer from a decimal string so I use
>
>mpz_set_str(rop, str, 10);
>
>Now, the thing is that I want to have total control over memory management 
>so I pre-allocate a buffer for rop and initialize all the header instead of 
>calling mpz_init (I know this is bad but I have to do that for efficiency).
>
>My question is: Given that the decimal string has N digits, how many limbs 
>should be allocated to rop so that it is guaranteed that GMP won't 
>re-allocate the buffer for rop?
>
>Mathematically, N decimal digits should fit in ceil( N * ln(10)/ln(B) ) 
>limbs where B is either 2^32 or 2^64. However, even when I allocate these 
>many limbs to rop GMP still re-allocate the buffer of rop. Why does GMP 
>have to reallocate memory when it is not necessary?
>
>Thanks,
>
>Minh

I don't know if this can help, but have you took a look at mpz_init2 ?
You can initialize variables, just as mpz_init does, but pre-allocating 'n' 
bits.

So, if you know, for example, that you may have numbers that grow and grow 
up to a certain maximum size in bits, you can use mpz_init2 and specify that 
maximum number of bits.  You also don't have to worry about limbs size as 
you just tell the number of 'bits' wanted.

Appart from alocating the specified number of bits, the variables 
initialized with mpz_init2 work exactly like one initialized with mpz_init, 
re-allocating memory if that 'maximum' come to not be enough.

You don't have to worry in any cases of wastefull downsize re-allocation as 
GMP never re-allocate a variable to 'free some limbs'.

Eric.

_________________________________________________________________
The new MSN 8 is here: Try it free* for 2 months 
http://join.msn.com/?page=dept/dialup