from math import sqrt, cbrt, log, e
from decimal import Decimal, getcontext


# 配置Decimal精度
getcontext().prec = 8


# 1D 标量类
class Scalar(Decimal):
    pass


def sqrt(self) -> 'Scalar':
    """计算平方根"""
    return Scalar(sqrt(float(self)))


def cbrt(self) -> 'Scalar':
    """计算立方根"""
    return Scalar(cbrt(float(self)))


def log(self, base: float = e) -> 'Scalar':
    """计算对数"""
    if float(self) <= 0:
        raise ValueError("对数的底数必须为正数")
    return Scalar(log(float(self), base))


def rooting(other: Scalar, self: Scalar) -> Scalar:
    """计算self的other次方根"""
    if float(other) == 0:
        raise ValueError("根指数不能为0")
    return self ** (Scalar(1) / other)


def tetration(a: Scalar, n: int, b: Scalar) -> Scalar:
    """迭代幂运算: a↑↑n = a^(a^(...^a)) (n次迭代，初始值为b)"""
    if n < 0:
        raise ValueError("迭代次数必须是非负整数")
    result = b
    for _ in range(n):
        result = a ** result
    return result


def knuth_arrow(a: Scalar, k: int, b: Scalar) -> Scalar:
    """高德纳箭头表示法: a↑^k b"""
    if k < 1:
        raise ValueError("高德纳箭头层级k必须≥1")
    if k == 1:
        return a * b
    elif k == 2:
        return a ** b
    else:
        result = b
        # 注意：对于k≥3且a较大时会导致运算结果极大，可能溢出
        for _ in range(int(a)):
            result = knuth_arrow(a, k - 1, result)
        return result