Advertisement
makispaiktis

Codewars - Digital Root

Jan 9th, 2021 (edited)
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. '''
  2. Digital root is the recursive sum of all the digits in a number.
  3. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way
  4. until a single-digit number is produced. The input will be a non-negative integer.
  5. Examples
  6.    16  -->  1 + 6 = 7
  7.   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
  8. 132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
  9. 493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2
  10. '''
  11.  
  12. def digitalRoot(n):
  13.     if n <= 0 or n != int(n):
  14.         print("Error while using the function '" + digitalRoot.__name__ + "'")
  15.         return -1000
  16.     if n >= 1 and n <= 9:
  17.         return n
  18.     else:
  19.         N = str(n)
  20.         SUM = 0
  21.         for i in range(len(N)):
  22.             SUM += int(N[i])
  23.         return digitalRoot(SUM)
  24.  
  25.  
  26. # MAIN FUNCTION
  27. print(digitalRoot(16))
  28. print(digitalRoot(942))
  29. print(digitalRoot(132189))
  30. print(digitalRoot(493193))
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement