Search code examples
cgmp

GMP mpz_sizeinbase returns size 2 for 9 in base 10


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?


Solution

  • 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 with mpz_get_str and then use strlen from C Standard library (<string.h>):

    printf(" has exact length %zu in base %d\n",
        strlen(mpz_get_str(NULL, base, n)), base);
    

    Output:

    90 has exact length 2 in base 10
    

    There is one caveat though, for a negative number you may need to substract one, as string representation includes - sign.