Skip to main content
 首页 » 编程设计

python之没有循环 Python 的数字根

2025年05月04日9bjzhanghao

def digit_sum(n): 
    '''(int)->number 
    Returns the sum of all the digits in the given integer, n''' 
    if n<10: 
        return n 
    return n%10 + digit_sum(n//10) 
 
def digital_root(n): 
    '''(int)->number 
    Returns the resulting sum of the digits in the given integer until it reaches a single digit number; via digit_sum''' 
    while n>9:       
        n=sum(digit_sum(n)) 
    return n 

写了digit_sum的代码,然后用递归写出了digital_root。我该怎么做?感谢您的帮助!

请您参考如下方法:

Wikipedia列出了数字根的简单 O(1) 公式:

def digit_root(n):  
    return (n - 1) % 9 + 1 

这里不考虑小于1的输入,所以可以修改如下,假设输入是整数:

def digit_root(n):  
    return (n - 1) % 9 + 1 if n else 0 

例子:

>>> digit_root(1) 
1 
>>> digit_root(11) 
2 
>>> digit_root(235) 
1