在Python中对于非常大的数字使用pow还是**?

14 投票
1 回答
16625 浏览
提问于 2025-04-18 07:05

我在用Python计算一些 num1**num2 的值。但是问题是,num193192289535368032L,而 num284585482668812077L,这两个数字都非常大。

我尝试了几种方法:首先,我用 ** 运算符来计算。但这花了太多时间(我等了大约两个小时,但没有得到结果)。

其次,我用了 math.pow(num1, num2)。但是得到了这样的结果:

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

最后,我用了 numpy.power

numpy.power(84585482668812077, 93192289535368032)
-9223372036854775808

如你所见,它给了我一个负数。

我真正想做的是 result = (num1**num2) 然后再计算 result % num3。所以,我需要高效地计算这个幂值。

我该怎么做呢?

1 个回答

25

你应该把 num3 作为第三个参数传给 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).

撰写回答