c++ - 在 mpz_t (MPIR) 中分配多少空间?

标签 c++ c mpir

假设我知道我的号码可能有多少位数(并且我想第一次分配合适的空间量,我如何计算我需要分配的字节数?我想我总是可以设置值是 1*10^(num digits),然后是 0,但感觉不对,好像我没有达到目的。

为清楚起见进行编辑:我想知道我需要多少字节来存储具有 n 十进制数字的整数,以及 MPIR 的实现是否会影响它。 @JonathonLeffler 在对他的回答的评论中提供了正确答案。

最佳答案

因为有一个 MPIR 标签,这可能是关于 MPIR , GMP 的一个分支。在当前文档(仅 PDF——没有在线 HTML)中,在“初始化整数”标题下,您可以找到:

void mpz_init2(mpz_t integer, mp_bitcnt_t n)

Initialize integer, with space for n bits, and set its value to 0. n is only the initial space, integer will grow automatically in the normal way, if necessary, for subsequent values stored. mpz_init2 makes it possible to avoid such reallocations if a maximum size is known in advance.

如果这是 GMP , 您可以在 Initializing integers 上阅读在线手册寻找:

— Function: void mpz_init2(mpz_t x, mp_bitcnt_t n)

Initialize x, with space for n-bit numbers, and set its value to 0. Calling this function instead of mpz_init or mpz_inits is never necessary; reallocation is handled automatically by GMP when needed.

While n defines the initial space, x will grow automatically in the normal way, if necessary, for subsequent values stored. mpz_init2 makes it possible to avoid such reallocations if a maximum size is known in advance.

In preparation for an operation, GMP often allocates one limb more than ultimately needed. To make sure GMP will not perform reallocation for x, you need to add the number of bits in mp_limb_t to n.

两者本质上是一样的。

关于c++ - 在 mpz_t (MPIR) 中分配多少空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913049/

相关文章:

c++ - 从函数返回 mpz_t

python - 在Visual Studio的Windows上安装MPIR时遇到问题吗?

c++ - MPIR gcc 编译 - 找不到 -lmpir

c++ - 为什么下面是 `s.clear(ios::badbit);`?为什么不是 `s.clear(ios::failbit);` ?

c++ - 如何获得适合 gpu 内存的最大数组大小?

c++ - 在 opencv c++ 中确定 StatModel 的类型

c++ - 与指向数组的指针 union

c - 在 C 中使用指针访问多维数组的最简单方法

android - GCC 6 移位溢出错误,

c - scanf 不会采用 &(*(p+i).grade)