假设我知道我的号码可能有多少位数(并且我想第一次分配合适的空间量,我如何计算我需要分配的字节数?我想我总是可以设置值是 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 forn
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 forn
-bit numbers, and set its value to 0. Calling this function instead ofmpz_init
ormpz_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 ton
.
两者本质上是一样的。
关于c++ - 在 mpz_t (MPIR) 中分配多少空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913049/