How to calculate 2 ^ -18 using GMP?

I just discovered, to my embarrassment, that suppressing negative metrics before mpz_pow_ui does not work very well. (β€œThe manual does say unsigned, you know.”) For other mpz_pow functions, the manual uses concepts that I don’t understand. For example, "base ^ exp mod mod" is as follows:

 void mpz_powm (mpz_t rop, mpz_t base, mpz_t exp, mpz_t mod) void mpz_powm_ui (mpz_t rop, mpz_t base, unsigned long int exp, mpz_t mod) Set _rop_ to _base_^_exp_ mod _mod_. 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. 

In the following code, what do I need to change so that it can handle negative metrics?

 #define Z(x) mpz_t x; mpz_init( x ); BSTR __stdcall IBIGPOWER(BSTR p1, long p2 ) { USES_CONVERSION; Z(n1); Z(res); LPSTR sNum1 = W2A( p1 ); mpz_set_str( n1, sNum1, 10 ); mpz_pow_ui( res, n1, p2 ); char * buff = (char *) _alloca( mpz_sizeinbase( res, 10 ) + 2 ); mpz_get_str(buff, 10, res); BSTR bResult = _com_util::ConvertStringToBSTR( buff ); return bResult; } 
+4
source share
5 answers

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

+7
source

I will not cut the code for you, but I will inform you that:

2 -n = 1 / 2 n

So, you can simply pass a positive exponent, then divide 1 by this number (and select a non-integer type of type mpf_t - type mpz_t is an integral, so it cannot represent real numbers like 2 -18 ).

+9
source

I don't know anything about GMP, but:

 2 ^ -18 

is equivalent to:

 1 / (2 ^ 18) 

So, why not write a function that processes negative metrics this way?

+2
source

A negative exp is supported if inverse mod-1 mod mod exists (see mpz_invert in Section 5.9 [Number Theoretical Functions], page 35). If inverse does not exist, then division by zero is increased.

If you talk about this, it is connected with number theory. A division or, more precisely, the converse to multiplication, exists only under certain conditions. I don’t remember the rules exactly, but basically it means that the division operation will not work if the mod-1 mod mode does not exist.

+1
source

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

0
source

All Articles