How does one calculate 2 ^ -18 ?

Décio Luiz Gazzoni Filho decio at
Wed Jan 7 16:43:53 CET 2009

On Jan 7, 2009, at 12:50 AM, Bruce M. Axtens wrote:

> Please pardon the mathematical naivete: I passed -18 to mpz_pow_ui and
> the code crashed. No surprises there ("read the friendly manual, you
> goose!")  So I went back to the manual and tried to get my mind around
> mpz_powm and related things. I'm still as confused as before. Please,
> someone, take pity on me and demonstrate in a bit of C how to raise  
> 2 to
> the negative 18.

2^-18 is not an integer, so it's no surprise that you didn't get a  
meaningful result out of trying to do an integer powering operation  
(mpz_pow). Whether that was a crash or an invalid value is beside the  
point. Just so you know, mpz_pow_ui actually takes an (u)nsigned  
(i)nteger as an exponent, as the name says. So rather than compute  
2^(-18), you computed something like 2^4294967278 assuming you were on  
a 32-bit computer, or maybe 2^18446744073709551598 if you were on a 64- 
bit computer, due to 2's complement representation of integers in your  
computer. GMP probably just ran out of memory -- although it's a  
`mere' 512 MB of RAM for the 32-bit case, I assume you can't allocate  
that much memory on the stack without special measures.

Now I have no idea what you want to do, since you didn't explain, so  
I'll just guess. If you're doing some kind of crypto or number theory,  
I presume you want to compute 2^(-18) mod n for some n. In that case,  
powering to a negative exponent is defined by inverting 2 modulo n  
(assuming that's possible, which as I recall happens as long as  
gcd(2,n) = 1), then powering to the absolute value of the exponent.  
Concretely, you first compute x = 2^(-1), i.e. the inverse of 2, then  
compute x^18, which works out to (2^(-1))^18 = 2^(-18). The manual  
indicates that mpz_powm will do the inversion automatically for you,  
as long as it exists, obviously.

Now if you're actually looking for the numbers 1/262144 or  
0.000003814697265625, maybe you should be using mpq or mpf instead.


More information about the gmp-discuss mailing list