How does one calculate 2 ^ -18 using GMP?

爱⌒轻易说出口 提交于 2019-12-05 11:57:34

The mpz_t data type can only store integers, and 2-18 is not an integer. To calculate that, you'll have to use the floating-point type mpf_t or the rational number type mpq_t.

I won't cut the code for you but I will make you aware that:

2-n = 1/2n

So you can just pass the positive exponent then divide 1 by that number (and choose a non-integer type like mpf_t - the mpz_t type is integral so cannot represent real numbers like 2-18).

I don't know much about GMP but:

2 ^ -18

is equivalent to:

1 / (2 ^ 18)

So why not write a function that handles negative exponents in this way?

Negative exp is supported if an inverse base-1 mod mod exists (see mpz_invert in Section 5.9 [Number Theoretic Functions], page 35). If an inverse doesn’t exist then a divide by zero is raised.

If you're talking about that, that's involves number theory. Division, or more precisely inverse of multplication, only exists on certain conditions. I don't exactly remember the rules, but basically it's saying that the division operation won't work if base-1 mod mod doesn't exist.

What you need to do depends on what you want to happen with the bits that will lost in the operation. Since you are dealing with integers, raising to a negative power implies division (well, reciprocation), but GMP offers several forms of division.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!