I want to write a function that can exponentiate a base number N times by a same exponent. For example, if I want to square a base number 2 three times, i.e. to calculate 2^2^2^2, the expected answer is 256. This seems trivial and I wrote the following recursive function:
def exponentiate_n_times(base, exponent, n):
if n == 0:
return base**exponent
return exponentiate_n_times(base**exponent, exponent, n=n-1)
However, the output is incorrect:
print(exponentiate_n_times(2, 2, 3))
# 65536
Then I tried this in Python:
2**2**2**2
and it also returns
65536
This is very confusing to me because I was expecting 256.
I don't know what's wrong with my function. Can anyone suggest the right way to exponentiate a number N times?