Is there an easy way to determine the number of digits a GMP integer has? I know you can determine it through a log, but I was wondering if there was something built into the library that I’m missing. The only thing I’ve found in the manual is:
_mp_size The number of limbs, or the negative of that when representing a negative integer.
Zero is represented by _mp_size set to zero, in which case the _mp_d data is unused.
But I’m under the impression that is quite different than what I’m looking for.
i.e
124839 = 6 digits.
You can use
size_t mpz_sizeinbase (mpz_t op, int base)to get the number of characters to output the number as a string in a specific base.So something along the lines of:
should be a good start.
If you want the exact size, you can use that value to create a big enough buffer, output the value to that buffer, then do a
strlento get the more accurate size, something like:Note that it’s not the most efficient way since it allocates a buffer every time you want to find the length, and it defaults to the safest size if the allocation fails, which could be one larger than necessary.
Another possible way is to use the safer
snprintfoption, since that returns the number of bytes that would have been written, and prevents buffer overflow:I haven’t tested that specifically but it’s a trick I’ve used for "regular" C-style printing before.
Note that both those "exact size" solutions include an optional sign at the front. If you want to truly count the digits rather then the characters, you should adjust for that (subtracting one from the size if the number is less than zero, for example).