I'm trying to use libgmp and I encountered something strange using mpz_sizeinbase. If I use a number which starts by base - 1 the size is one too big.
#include <gmp.h>
mpz_t n;
int main() {
unsigned int base = 10;
mpz_init_set_str (n, "90", base);
mpz_out_str(stdout, base, n);
printf(" has length %zu in base %d\n", mpz_sizeinbase (n, base), base);
}
when I run it:
$ gcc -g draft.c -o draft -lgmp && ./draft
90 has length 3 in base 10
Am I doing something wrong?
Note The last statement.
the right amount of allocation is normally two more than the value returned by mpz_sizeinbase, one extra for a minus sign and one for the null-terminator.
Similar question here worth looking at it
The kkk's answer already explained the result of
mpz_sizeinbase
. However, if you want to obtain exact length in decimal base, you can convert it into character array withmpz_get_str
and then usestrlen
from C Standard library (<string.h>
):Output:
There is one caveat though, for a negative number you may need to substract one, as string representation includes
-
sign.