This is how we do super fast exponents, i.e. powers.
Let’s say that we want to calculate . Binary exponentiation will divide by 2 recursively. For example,
So the recursive formula is:
In terms of code:
def pow(x, n):
if n == 0: return 1.0
# if n is -ve, we need to take reciprocals
if n < 0: return 1/pow(x, -n)
# if even, we just divide
if n % 2 == 0:
return pow(x*x, n/2)
# if odd, we take out one of x
else:
return x * pow(x*x, (n-1)/2)