Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pow or ** for very large number in Python

I am trying to calculate some num1**num2 in Python. But the problem is that num1 is 93192289535368032L and num2 is 84585482668812077L, which are very large numbers.

I tried several methods as follows: First, I tried to calculate it by using the ** operator. But it took too much time (I waited about 2 hours, but I got no result).

Second, I used math.pow(num1, num2). But I got this:

Traceback (most recent call last):   File "<pyshell#23>", line 1, in <module>
    math.pow(84585482668812077L, 93192289535368032L)
OverflowError: math range error

Finally, I used numpy.power:

numpy.power(84585482668812077, 93192289535368032)
-9223372036854775808

As you see, it gave me minus.

What I really want to do is result = (num1**num2) and then the result % num3. So, I need to calculate this power value efficiently.

How can I do this?

like image 669
GoodGJ Avatar asked May 20 '14 11:05

GoodGJ


1 Answers

You should pass num3 as the 3rd parameter to pow

pow(...)
    pow(x, y[, z]) -> number

    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
like image 142
John La Rooy Avatar answered Oct 09 '22 06:10

John La Rooy