1

Supposing that I know how many digits my number might be (and I'd like to allocate the right amount of space the first time, how can I calculate the number of bytes I need to allocate? I suppose I could always set the value to be 1*10^(num digits) and then 0 after but that feels wrong, and like I'm defeating the purpose.

Edit for clarity: I want to know how many bytes I need to store an integer with n decimal digits, and whether or not MPIRs implementation might affect that. @JonathonLeffler provided the correct answer in the comment to his answer.

Maria
  • 565
  • 6
  • 20

1 Answers1

4

Since there is an MPIR tag, this is probably about MPIR, a fork of GMP. And in the current documentation (PDF only — no online HTML), under the heading 'Initializing integers', you can find:

void mpz_init2(mpz_t integer, mp_bitcnt_t n)

Initialize integer, with space for n bits, and set its value to 0. n is only the initial space, integer will grow automatically in the normal way, if necessary, for subsequent values stored. mpz_init2 makes it possible to avoid such reallocations if a maximum size is known in advance.

If this was for GMP, you can read the online manual on Initializing integers to find:

— Function: void mpz_init2(mpz_t x, mp_bitcnt_t n)

Initialize x, with space for n-bit numbers, and set its value to 0. Calling this function instead of mpz_init or mpz_inits is never necessary; reallocation is handled automatically by GMP when needed.

While n defines the initial space, x will grow automatically in the normal way, if necessary, for subsequent values stored. mpz_init2 makes it possible to avoid such reallocations if a maximum size is known in advance.

In preparation for an operation, GMP often allocates one limb more than ultimately needed. To make sure GMP will not perform reallocation for x, you need to add the number of bits in mp_limb_t to n.

The two are essentially the same.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Yes, I read this documentation. My question, I suppose, is more about how I calculate the number of maximum bits I need based on the maximum number of digits I am allowed. It's not the end of the world though, a minor optimization. – Maria Jan 13 '15 at 19:01
  • If you know the number of decimal digits, then the number of bits needed is approximately log2(10) * decimal_digits, isn't it? It helps you get the right answer if you ask the question clearly — and include background information on what you know and what you want explained. – Jonathan Leffler Jan 13 '15 at 19:15
  • 1
    That is what I was looking for, just a bit unsure about whether MPIRs implementation might have an effect. No one intentionally asks a question badly. – Maria Jan 13 '15 at 20:00