Pow or ** for a very large number in Python

I am trying to compute 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: firstly, I tried to calculate it using the ** operator. But it took too much time (I waited about 2 hours, but did not get the result).

Secondly, 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 can see, this gave me a minus.

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

How can i do this?

+9
source share
1 answer

You should pass num3 as the third 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 (eg for longs).
+15
source

Source: https://habr.com/ru/post/969573/


All Articles