0
votes

I use gmp library write a C program like

len = mpz_sizeinbase(res, 10);

when res = 9, it gives me 2. So i check manual and it says

    size_t mpz_sizeinbase (mpz_t op, int base)

Return the size of op measured in number of digits in the given base. base can vary from 2 to 62. The sign of op is ignored, just the absolute value is used. The result will be either exact or 1 too big. If base is a power of 2, the result is always exact. If op is zero the return value is always 1.

I just want to know why this function design with this leak? Why CAN'T it be exact?

Some question i found similar :

GMP mpz_sizeinbase returns size 2 for 9 in base 10

Number of digits of GMP integer

1
The implementation and the comment above probably shades some light...KamilCuk

1 Answers

2
votes

mpz_sizeinbase does not look at the whole number but only at the highest word. It then estimates the size. Problem is that it might be looking at 999999999 or 1000000000. To know exactly which of the two it is all bits of the number would have to be looked at. What mpz_sizeinbase does is (using word == digit for the example) compute the size for 9xxxxxxxx. The xxxxxxxx part is ignored and could cause an overflow of the first digit. So the size is increased by one and returned.

This lets you allocate enough space for coneverting the number quickly with only a minimal waste in some cases. The alternative would be to convert the whole number just to get the size, allocate the buffer and then do it all over again to actually store the result.