pow or ** for very large number in Python
11,685
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).
Comments
-
GoodGJ almost 2 years
I am trying to calculate some
num1**num2
in Python. But the problem is thatnum1
is93192289535368032L
andnum2
is84585482668812077L
, 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 theresult % num3
. So, I need to calculate this power value efficiently.How can I do this?
-
GoodGJ almost 10 yearsThanks. I think I have to import "math" for using pow. But there is default pow in Python itself.
-
DSM almost 10 yearsYou don't want to import
pow
frommath
-- that's the Cpow
, which doesn't accept the third argument. -
John La Rooy almost 10 years@confused_at_times,
math.pow
does the calculation in floating point. The loss of precision is unacceptable here even if result fits in the floating point range. Also it's really not practical to just do the mod at the end when large numbers are involved. -
confused_at_times almost 10 yearsSorry, comment was based on not reading the question properly. Didn't realise user had already tried that.