Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GMPY2 (or GMP) have a pow() function?

Tags:

python

gmp

gmpy

GMPY2 (or GMP) has a powmod function but I can't find anything for regular exponentiation aside from python's native pow. Does a function like this exist for mpz integers?

like image 443
qwr Avatar asked May 17 '14 20:05

qwr


2 Answers

Just use Python's standard pow() function or the exponentiation ** operator. GMPY2's mpz type overloads all the standard special methods so you should just be able to use standard Python commands.

For example:

>>> from gmpy2 import mpz
>>> pow(mpz(3),7)
mpz(2187)
>>> pow(mpz(3),7,13)
mpz(3)
>>> mpz(3)**7
mpz(2187)
>>> 

The same holds true for divmod(), etc.

like image 52
casevh Avatar answered Sep 20 '22 15:09

casevh


Some performance information:

gmpy2 pow is twice as fast as python's pow, even when factoring in construction:

>>> timeit.timeit('pow(98765, 10)', number=100000)
0.048412954514788
>>> timeit.timeit('pow(gmpy2.mpz(98765), 10)', number=100000, setup='import gmpy2')
0.024286470230094892

You can use the built-in pow(x,y,modulus) on an mpz, but using powmod instead is a about 10% faster.

>>> timeit.timeit('pow(gmpy2.mpz(987654321),1000,100003)', 
number=100000, setup='import gmpy2')
0.057212181510976734
>>> timeit.timeit('gmpy2.powmod(987654321,1000,100003)', 
number=100000, setup='import gmpy2')
0.04513445007546579
>>> timeit.timeit('pow(987654321,1000,100003)', 
number=100000, setup='import gmpy2')
0.15511784474188062

The gmpy2 version is much faster than the native python with a modulus (sometimes as much as 10 times faster). Using powmod is only marginally faster than using pow/mpz, because of the construction time of the mpz.

If you already have an mpz, powmod and pow are aboslutely equivalent.

like image 27
Erik Aronesty Avatar answered Sep 23 '22 15:09

Erik Aronesty