不带**(Python)的指数(乘法)

不带**(Python)的指数(乘法),python,math,exponential,Python,Math,Exponential,如何执行此操作: if p1 == 0: return 1 if p1 == 1: return temp_obj if p1 == 2: return temp_obj*temp_obj if p1 == 3: return temp_obj*temp_obj*temp_obj if p1 == 4: return temp_obj*temp_obj*temp_obj*temp_obj 不用** 我实际上是在一个重载pow的类中编写的,*已经重载了 我

如何执行此操作:

if p1 == 0:
    return 1
if p1 == 1:
    return temp_obj
if p1 == 2:
    return temp_obj*temp_obj
if p1 == 3:
    return temp_obj*temp_obj*temp_obj
if p1 == 4:
    return temp_obj*temp_obj*temp_obj*temp_obj
不用**

我实际上是在一个重载pow的类中编写的,*已经重载了

我试过了

for x in range(p1):
  temp_obj = temp_obj * temp_obj
但那没用。价值非常高


谢谢你的尝试无效,因为当你修改temp_obj时,你不再用它的原始值乘以它。您也可以尝试以下方法:

initial_value = temp_obj
for x in range(p1):
  temp_obj = temp_obj * initial_value

假设乘法是相联的,您可以通过平方(
O(logn)
)使用幂运算:


这不起作用的原因是,你要对每一个幂的值进行平方运算。这意味着对于
p1=3
,我们得到:

temp_obj = 5
temp_obj = temp_obj * temp_obj = 25
temp_obj = temp_obj * temp_obj = 625
temp_obj = temp_obj * temp_obj = 390625
所以你实际计算了523。所以58=390'625

我们可以通过每次乘以该值来解决此问题,因此:

def power(x, p):
    if not p:
        return 1
    y = x
    for x in range(p-1):
        y *= x
    return y
但这适用于线性时间,我们也可以在对数时间构造算法:

def power(x, p):
    if p == 0:
        return 1
    elif p & 1:
        return x * power(x*x, p//2)
    else:
        return power(x*x, p//2)
或者,如果我们想减少递归调用的开销,那么命令式版本:

def power(x, p):
    r = 1
    while p:
        if p & 1:
            r *= x
        x *= x
        p >>= 1
    return r
例如:

>>> power(5, 6)
15625
>>> power(5, 1)
5
>>> power(5, 0)
1
>>> power(3, 2)
9
>>> power(3, 7)
2187

您可以使用递归函数。@internet\u用户。好主意,它确实需要更多的簿记+1在将该名称用于其他名称之前,您是否可以重命名
pow
?为什么要重新发明轮子来解决名称空间问题?@JohnColeman。不太可靠,用户出错的可能性很高late@ShpielMeister隐藏内置函数也不是很健壮。找到一种解决名称问题的方法似乎比重写功能要好。OP说,数字非常大
math.pow()
很容易溢出。只是尝试了一下,但没有成功。temp_obj*temp_obj是我之前已经重载的字典。与我想要的结果相比,我的结果非常大。我调用了power(temp_obj,p1),但出于某种原因,我的返回值为0。@MTG:使用什么参数?temp_obj是我初始化的字典对象,p1是int。@MTG:initialized dictionary?你无法计算字典的威力。我用一些值对它进行了测试(见编辑后的答案)。但如果我乘以…temp_obj*temp_obj…,它就会工作。。。。(我超载*并创建了自己的乘法dicts)
>>> power(5, 6)
15625
>>> power(5, 1)
5
>>> power(5, 0)
1
>>> power(3, 2)
9
>>> power(3, 7)
2187