GMP mpz_sizeinbase returns 大小 2 for 9 in base 10

GMP mpz_sizeinbase returns size 2 for 9 in base 10

我正在尝试使用 libgmp,但在使用 mpz_sizeinbase 时遇到了一些奇怪的事情。如果我使用以 base - 1 开头的数字,则尺寸太大了。

#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);
}

当我 运行 它:

$ gcc -g draft.c -o draft -lgmp && ./draft
90 has length 3 in base 10

我是不是做错了什么?

注意最后一句。

正确的分配量通常比mpz_sizeinbase返回的值多两倍,负号多一倍,空终止符多一倍。

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.

This function can be used to determine the space required when converting op to a string. 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

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 然后使用 C 标准库中的 strlen (<string.h>):

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

输出:

90 has exact length 2 in base 10

不过有一点需要注意,对于负数,您可能需要减一,因为字符串表示形式包括 - 符号。