1

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?

Shaun Han
  • 2,676
  • 2
  • 9
  • 29
  • 3
    2^2^2^2 = 2 ^ (2 ^ (2 ^ 2)) = 2 ^ (2 ^4 ) = 2 ^ 16 – Farhood ET Aug 03 '21 at 13:53
  • 3
    `2**2**2**2` is parsed as `2**(2**(2**2)))`, rather than `((2**2)**2)**2` which is indeed 256. – jasonharper Aug 03 '21 at 13:54
  • 1
    "This is very confusing to me because I was expecting 256." I don't understand why. 65536 is the answer you get following the normal mathematical rules. Please see for example https://math.stackexchange.com/questions/439075/incorrect-notation-in-math . – Karl Knechtel Aug 03 '21 at 13:56
  • 3
    If you want to repeatedly do the same thing, a loop is generally a better idea than recursion. – Karl Knechtel Aug 03 '21 at 13:58
  • @jasonharper I thought arithmetic operations always start from left to right (assuming no parentheses and same operation)? – Shaun Han Aug 03 '21 at 14:02
  • 2
    @Shaun Han: the ```**``` operator binds from right to left. – sj95126 Aug 03 '21 at 14:04
  • 1
    See [operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) – Mark Tolonen Aug 03 '21 at 14:08
  • ``return exponentiate_n_times(base**exponent, exponent, n=n-1)`` should be ``return exponentiate_n_times(base, exponent, n=n-1)**exponent``. The base case should be ``base`` for ``n==1``. – MisterMiyagi Aug 03 '21 at 14:11

1 Answers1

2

So you want to calculate base ** (exponent ** n), and since the operator ** already binds right to left, we can skip the brackets:

def exponentiate_n_times(base, exponent, n):
    return base ** exponent ** n

exponentiate_n_times(2, 2, 3) # 256
exponentiate_n_times(3, 2, 3) # 6561
exponentiate_n_times(3, 3, 3) # 7625597484987
Jan Christoph Terasa
  • 5,781
  • 24
  • 34