forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigital_root.py
More file actions
46 lines (37 loc) · 1.16 KB
/
Copy pathdigital_root.py
File metadata and controls
46 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from __future__ import annotations
"""
Digital Root.
The digital root (also known as the repeated digital sum) of a non-negative
integer is the (single digit) value obtained by an iterative process of summing
digits: on each iteration the digits of the previous result are summed, and the
process continues until a single-digit number is reached.
For more information see:
https://en.wikipedia.org/wiki/Digital_root
"""
def digital_root(number: int) -> int:
"""
Return the digital root of a non-negative integer number.
The digital root is the single-digit value obtained by repeatedly summing
the decimal digits of number until only one digit remains. The input is taken by
its absolute value, so negative numbers behave like their positive
counterpart.
>>> digital_root(0)
0
>>> digital_root(9)
9
>>> digital_root(38)
2
>>> digital_root(12345)
6
>>> digital_root(-45)
9
>>> digital_root(999999999999)
9
"""
number = abs(number)
while number >= 10:
number = sum(int(digit) for digit in str(number))
return number
if __name__ == "__main__":
import doctest
doctest.testmod()