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).
Share:
11,685
GoodGJ
Author by

GoodGJ

I will be a dentist, doing programming.

Updated on June 20, 2022

Comments

  • GoodGJ
    GoodGJ almost 2 years

    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?

  • GoodGJ
    GoodGJ almost 10 years
    Thanks. I think I have to import "math" for using pow. But there is default pow in Python itself.
  • DSM
    DSM almost 10 years
    You don't want to import pow from math-- that's the C pow, which doesn't accept the third argument.
  • John La Rooy
    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
    confused_at_times almost 10 years
    Sorry, comment was based on not reading the question properly. Didn't realise user had already tried that.