fork download
  1. # Digital roots.
  2. # @see en.wikipedia.org/wiki/Digital_root
  3.  
  4. # Formal definition.
  5. # A natural number n is a digital root if it is a fixed point for digit_sum
  6. # (which occurs if digit_sum(n) equals n).
  7.  
  8. def fixed_point(f, guess, equal):
  9. while not equal(guess, result := f(guess)):
  10. guess = result
  11. return guess
  12.  
  13. def digit_sum(n):
  14. return sum(map(int, str(n)))
  15.  
  16. def digital_root_1(n: int) -> int:
  17. return fixed_point(digit_sum, n, lambda x, y: x == y)
  18.  
  19. # Direct formulas.
  20.  
  21. def digital_root_2(n: int) -> int:
  22. if n == 0:
  23. return 0
  24. n %= 9
  25. return n if n != 0 else 9
  26.  
  27. def digital_root_3(n: int) -> int:
  28. if n == 0:
  29. return 0
  30. return 1 + (n - 1) % 9
  31.  
  32. def digital_root_4(n: int) -> int:
  33. if n == 0:
  34. return 0
  35. return n - (n - 1) // 9 * 9 # flooring division
  36.  
  37. # Show.
  38.  
  39. def digital_root_show_all(n):
  40. fs = [
  41. digital_root_1,
  42. digital_root_2,
  43. digital_root_3,
  44. digital_root_4
  45. ]
  46. for f in fs:
  47. print(list(map(f, range(n))))
  48.  
  49. if __name__ == '__main__':
  50. digital_root_show_all(12)
Success #stdin #stdout 0.1s 14104KB
stdin
Standard input is empty
stdout
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]