我在Python中实现了exponentiation by squaring algorithm
(x,n)=(input(),input())
def exp_itr(x,n):
r=1
while n!=0:
if n%2==1:
r=r*x
n=n-1
x=x*x
n=n/2
return r
现在,我需要递归算法。我该怎么办?
答案 0 :(得分:1)
这是评论中提到的pseudocode的Python版本
def exp(x, n):
if n < 0:
return exp(1 / x, -n)
elif n == 0:
return 1
elif n == 1:
return x
elif n % 2 == 0:
return exp(x * x, n / 2)
else:
return x * exp(x * x, (n - 1) / 2)