Digital Root without loops Python

Question:

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

Wrote the code for digit_sum and then used recursion to write digital_root. How would I go about this? Any help is appreciated!

Asked By: user7066909

||

Answers:

Wikipedia lists a simple O(1) formula for the digital root:

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

This does not take into account an input less than 1, so you can modify as follows, with the assumption that the input is a whole number:

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

Examples:

>>> digit_root(1)
1
>>> digit_root(11)
2
>>> digit_root(235)
1
Answered By: brianpck

So the idea is that you have to use recursion for the last one as well? In that case, this should do the job:

def digital_root(n):
    if n < 10:
        return n
    return digital_root(digit_sum(n))
Answered By: fuglede

Try this:

def num(n) :   
     sum = 0   #provided sum as 0
     for i in str(n): 
         a = int(n) % 10    #taken variable a 
         sum  = sum + a   #put the sum.
         n = n/10
     print(sum)    
     if sum < 10:    
         print(str(sum) + "=this is a digital root")
     else:
         num(sum)
Answered By: Himanshu Sharma

please try the following code:

def dgtl_rt(n):
   return n%9 or n and 9
print(dgtl_rt(123))
Answered By: shyam
def droot(a):
    while a>=10:
         b =int(a/10) #other digit(s)
         c =a-(b*10)  #the rightmost digit
         a =b+c #add together
    return a

I have not seen this solution anywhere, so I thought it would be nice to share, i discovered it myself! Just 1 looping structure.

Answered By: Russel Alfonso
{def MDR(n):
    '''
    this function returns multiplicative digital root.
    '''
    count, mdr = 0, n 
    while mdr > 9:
        m, digitsMul = mdr, 1
        while m:
            m, md = divmod(m, 10)
            digitsMul *= md
        mdr = digitsMul
        count += 1
    return count, mdr}
Answered By: Arpit Agarwal
def digital_root(n):
    while n > 9:
        n = sum(map(int, str(n))
    return n
Answered By: M.Zayniddin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.