Skip to content
scipython.com

P2.7.8Tetration

Tetration may be thought of as the next operator after exponentiation: where \(x \times n\) can be written as the sum \(x+x+x+\cdots + x\) with \(n\) terms, and \(x^n\) is the multiplication of \(n\) factors: \(x\cdot x \cdot x \cdots x\), the expression written \(^nx\) is equal to the repeated exponentiation involving \(n\) occurences of \(x\):

\[^nx = x^{x^{.^{.^x}}}\]

For example, \(^42 = 2^{2^{2^{2}}} = 2^{2^{4}} = 2^{16} = 65536\). Note that the exponential "tower" is evaluated from top to bottom.

Write a recursive function to calculate \(^nx\) and test it (for small, positive real values of \(x\) and non-negative integers \(n\): tetration generates very large numbers)!

How many digits are there in \(^35\)? In \(^52\)?

Show solution

The code below presents both recursive and non-recursive functions for calculating the tetration. \(^35\) has \(2185\) digits; \(^52\) has 19729 digits.

import math

def tet(x, n):
    """ Tetration, ^nx, by loop over decreasing exponent counter. """
    if n == 0:
        return 1
    p = x
    while n > 1:
        p = x**p
        n -= 1
    return p

def tet2(x, n):
    """ Tetration, ^nx, by recursion. """
    if n == 0:
        return 1
    return x**tet2(x, n-1)

x, n = 5, 3
t = tet2(x,n)
print('tet({:d}, {:d}) = {:d}'.format(x, n, t))
ndigits = int(math.log10(t)) + 1
print('(a number with {:d} digits)'.format(ndigits))