Digital root
- Lokendra Ved 
- Jun 5, 2020
- 1 min read
This problem is taken from codewars
Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
Examples
    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2Solution:
def digital_root(n):
    li = list(str(n))
    sum = 0
    for i in li:
        sum += int(i)
    if sum>9:
       return digital_root(sum)
    return sum
digital_root(16) #output 7
digital_root(942) #output 6
digital_root(132189) #output 6Happy Coding!
Follow us on Instagram @programmersdoor
Join us on Telegram @programmersdoor
Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.
Follow Programmers Door for more.
.png)



Comments