I implemented the exponentiation by squaring algorithm in Python

    (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

And now, I need the recursive algorithm. How can I do it?

有帮助吗?

解决方案

Here's a Python version of the pseudocode mentioned in comments

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top