🛠️ToolsShed

数字根计算器

通过反复对数字求和计算任意整数的数字根。逐步显示过程和加法持久性。

加法数字根: 反复对各位数字求和,直到剩下一位数字。

乘法数字根: 反复对各位数字求积,直到剩下一位数字。

常见问题

代码实现

def digit_sum(n: int) -> int:
    return sum(int(d) for d in str(abs(n)))

def digital_root(n: int) -> int:
    """Returns the additive digital root (1-9, or 0 for 0)."""
    if n == 0:
        return 0
    remainder = n % 9
    return remainder if remainder != 0 else 9

def additive_persistence(n: int) -> tuple[int, list[int]]:
    steps = [n]
    count = 0
    while n >= 10:
        n = digit_sum(n)
        steps.append(n)
        count += 1
    return count, steps

def multiplicative_digital_root(n: int) -> tuple[int, list[int]]:
    steps = [n]
    count = 0
    while n >= 10:
        product = 1
        for d in str(n):
            product *= int(d)
        n = product
        steps.append(n)
        count += 1
    return count, steps

n = 493
print(f"Digital root of {n}: {digital_root(n)}")
persistence, steps = additive_persistence(n)
print(f"Steps: {' -> '.join(map(str, steps))}")
print(f"Additive persistence: {persistence}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.